.NET Core Worker project "Start" with "0" argument(s) - .net-core

I got a worker project and I prepared a few things in it (mainly log4net with a config and a worker). When I run it from Visual Studio, it works perfectly fine, however...
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostContext, config) =>
{
config.AddJsonFile("appsettings.json", optional: true);
config.AddJsonFile($"appsettings.{hostContext.HostingEnvironment.EnvironmentName}.json", optional: true);
config.AddEnvironmentVariables();
})
.UseWindowsService()
.ConfigureLogging(logging =>
{
logging.AddLog4Net("log4net.config");
logging.AddConsole();
logging.SetMinimumLevel(LogLevel.Debug);
})
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<SomeWorker>();
// DI...
});
After using it as a Windows service, I receive an error. Am I missing something here? It seems that there isn't really much that could actually go wrong.
2020-04-28T14:11:27.2038348Z ##[section]Starting: Start Windows Service: ServiceName
2020-04-28T14:11:27.2038348Z ==============================================================================
2020-04-28T14:11:27.2038348Z Task : Start Windows Service
2020-04-28T14:11:27.2038348Z Description : Start a windows service.
2020-04-28T14:11:27.2038348Z Version : 8.0.0
2020-04-28T14:11:27.2038348Z Author : Michael Barry
2020-04-28T14:11:27.2038348Z Help : [More Information](https://github.com/jabbera/my-vsts-tasks)
2020-04-28T14:11:27.2038348Z ==============================================================================
2020-04-28T14:11:28.3796348Z Starting Windows Services ServiceName and setting startup type to: Automatic.
2020-04-28T14:11:28.9180348Z ##[error]Exception calling "Start" with "0" argument(s): "Cannot start service ServiceName on computer '.'."
2020-04-28T14:11:28.9648348Z ##[section]Finishing: Start Windows Service: ServiceName

You probably start the service without arguments. When you start the service from VS the Main method is called with a single startup argument (%LAUNCHER_ARGS%). When starting it as a Windows service this argument is probably missing.

Related

Add an endpoint to .Net Core 3.1 Worker Service

I have a Worker Service in .Net Core 3.1 created using the template in VS 2022
DI is Configured in Program.cs
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
...
services.AddTransient<DapperContext>();
var workerSettings = new WorkerSettings();
hostContext.Configuration.Bind(nameof(WorkerSettings), workerSettings);
services.AddSingleton(workerSettings);
var dataReadSettings = new DataReadSettings();
hostContext.Configuration.Bind(nameof(DataReadSettings), dataReadSettings);
services.AddSingleton(dataReadSettings);
services.AddHostedService<Worker>();
});
This Worker Service is deployed in K8, which complains about not having a "healthz" endpoint like so:
Readiness probe failed: Get "the ip address of the service/healthz": dial "tcp the same IP"
I would like to learn on how to do this as this will require, I think, adding a Web API like functionality since we need an http endpoint.
Appreciate the help and thanks in advance.

Dotnet 5 to 6 migration - application fails to start - How to use IIS?

I have migrated my web app from dotnet 5 to dotnet 6. Firstly, I updated dotnet version for all projects in solution, and then updated necessary nuget packages accordingly. After this, the application worked fine.
After that, I wanted to improve my Program.cs class, in order to get rid of Startup.cs. In dotnet 5, my program.cs looked like this:
public static int Main(string[] args)
{
.....
.....
var host = CreateHostBuilder(args).Build();
host.Run();
return 0;
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseNLog()
.ConfigureLogging((host, loggingBuilder) =>
{
loggingBuilder.ClearProviders();
if (host.HostingEnvironment.IsDevelopment())
{
loggingBuilder.AddConsole();
loggingBuilder.AddNLog(".\\nlog.config");
}
else
{
loggingBuilder.AddNLog(".\\nlog.config");
}
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseIIS();
webBuilder.UseStartup<Startup>();
});
I updated this to:
var builder = WebApplication.CreateBuilder(args);
builder.Host.ConfigureLogging((host, loggingBuilder) =>
{
loggingBuilder.ClearProviders();
if (host.HostingEnvironment.IsDevelopment())
{
loggingBuilder.AddConsole();
loggingBuilder.AddNLog(".\\nlog.config");
}
else
{
loggingBuilder.AddNLog(".\\nlog.config");
}
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseIIS();
//webBuilder.UseStartup<Startup>(); --> removed this
});
After this change, I get error:
I suspect, I cannot use ConfigureWebHostDefaults anymore. So how can I configure my app to UseIIS?
My hosting model is "InProc", and I cannot change that.
When I tried adding builder.Services.Configure<IISServerOptions>() or builder.WebHost.UseIIS();, but it only changed the error to:
The Event Logs show following two errors:
Application '/LM/W3SVC/1/ROOT/portal' with physical root 'C:\Users\zee\source\repos\Portal\Portal.Web\' has exited from Program.Main with exit code = '0'. Please check the stderr logs for more information.
Application '/LM/W3SVC/1/ROOT/portal' with physical root 'C:\Users\zee\source\repos\Portal\Portal.Web\' failed to load coreclr. Exception message: CLR worker thread exited prematurely
The docs HERE says that WebApplication.CreateBuilder calls Kestrel internally. How this behavior can be changed to use IIS instead?
I have tried few other things, but did not work.
Question:
Can someone point me to the right direction? Why there is no clear guidelines on using IIS? Several answers suggest that I should change to OutOfProc, which I cannot.

Unable to create an object of type 'AppContext'. Using verbose but

I tried to do my first migration and I got this error.
I used:
dotnet ef migrations add initial --project AppProject.Core --verbose
The error:
Finding application service provider in assembly 'AppProject.Core'...
Finding Microsoft.Extensions.Hosting service provider...
-> No static method 'CreateHostBuilder(string[])' was found on class 'Program'.
-> No application service provider was found.
Finding DbContext classes in the project...
Found DbContext 'AppContext'.
Microsoft.EntityFrameworkCore.Design.OperationException: Unable to create an object of type 'AppContext'.
My Program.cs
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
My Startup
services.AddDbContext<AppContext>(options =>
{
options.UseNpgsql(connection);
});
services.AddIdentity<User, IdentityRole<Guid>>()
.AddEntityFrameworkStores<SysFishingContext>()
.AddDefaultTokenProviders();
I don't get what is the problem. Please someone help me.
Try to specify both options --project and --startup-project
-p|--project <PROJECT>
This is the project that DbContext is sitting in.
-s|--startup-project <PROJECT>
This is the project with Depenedency Injection setup, usually the Web project.
Your migrations add command might look like below:
dotnet ef migrations add initial --startup-project AppProject.Web --project AppProject.Core --verbose

Configuring Rebus in a .net core Worker Service (or a Console App)

I have seen that Adding rebus in the ASP.NET Core execution pipeline is very neat using Startup.cs.
I wonder if there is a same neat way to do the same for Worker service or generally a console app.
Most .net core console apps I have seen are very simple demo applications.
Kindly if there is any concrete sample configuration using .net core console application.
Regards
Amour Rashid
One way would be to add Microsoft's Microsoft.Extensions.Hosting package and build your background service as a BackgroundService:
public class MyBackgroundService : BackgroundService
{
readonly IServiceCollection _services = new ServiceCollection();
public BackgroundService()
{
// configure the bus
services.AddResbus(
configure => configure
.Transport(t => t.Use(...))
);
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
using var provider = _services.BuildServiceProvider();
// start the bus
provider.UseRebus();
while (!stoppingToken.IsCancellationRequested)
{
await Task.Delay(TimeSpan.FromSeconds(1), stoppingToken);
}
}
}
which you then add by going
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<MyBackgroundService>();
});
in your startup.
Thanks Mogens,
Another way is to
var host =CreateHostBuilder(args).Build();
host.UseRebus();
host.Run();
Or in ConfigureServices method
....
var provider=services.CreateServiceProvider();
provider.UseRebus();
It helped me I could create Worker Services using rebus.

Running Kestrel yields empty browser

I've recently just upgraded Visual Studio 2015 with ASP.NET 5 beta8, which causes the strange shift from the old listener over to this new 'Kestrel' .. thing.
I've attempted to follow the instructions and get it to run, but I simply yield a console window that says...
Hosting environment: Development
Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.
Okay, so I navigate to http://localhost:5000, and ... nothing is there. My application doesn't run or anything.
I have tried to launch the default ASP.NET MVC sample project using Kestrel too, with the built in settings, and get the same result. I'm really unsure of what to do.
Here is what I've done so far...
I have it in my project.json file;
"dependencies": {
"Microsoft.AspNet.Server.Kestrel": "1.0.0-beta8",
},
"commands": {
"web": "Microsoft.AspNet.Server.Kestrel"
},
My program was working fine on beta7, using the old listener; But now even that doesn't work suddenly since installing beta8. I'm at the hair-pulling stage of frustration over this forced change. I can't get it to run in IIS either.
Per request, this is my Startup.cs file;
public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv) {
// Setup configuration sources.
Configuration = new ConfigurationBuilder()
.SetBasePath(appEnv.ApplicationBasePath)
.AddJsonFile("config.json")
.AddEnvironmentVariables()
.Build();
}
public IConfiguration Configuration { get; set; }
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services) {
// Add MVC services to the services container.
services.AddMvc();
services.UseCookieAuthentication(o => {
//o.ExpireTimeSpan
o.CookieName = "3b7eaa9c-decd-4c5d-83f9-01f1f11a6e22";
});
}
public void Configure(IApplicationBuilder app) {
app.UseIdentity();
app.UseStaticFiles();
app.UseMvc(routes => {
// add the new route here.
routes.MapRoute(name: "areaRoute",
template: "{area:exists}/{controller}/{action}");
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}"
);
});
}
That understand in which place the request pipeline problem arise, enable logging in your application.

Resources