I'm creating a .NET Core Worker Service, and want to expose ASP.Net Core Web APIs for the service. I'm using .NET Core 3.0. Initially, my plan was to replace IHostBuilder with IWebHostBuilder and add a Startup class just like a regular Asp.Net Core web app (this is probably an oversimplification, though).
My plan was to simply try to replace
public static IHostBuilder CreateHostBuilder(string[] args)
{
return Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<Worker>();
});
}
with
public static IWebHostBuilder CreateHostBuilder(string[] args)
{
return WebHost.CreateDefaultBuilder(args)
.ConfigureServices(services =>
{
services.AddHostedService<Worker>();
}).UseStartup<Startup>();
}
which may not work at all, but at least it's a starting point... What's blocking me from trying this approach is that I cannot implement my Startup
class because IWebHostEnvironment
is unavailable.
Here's my
<PropertyGroup>
<TargetFramework>netcoreapp3.0</TargetFramework>
<UserSecretsId>dotnet-WorkerServices-0E977A2C-F0C8-49E7-B00A-5EB01B99FBEB</UserSecretsId>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Hosting.Server.Abstractions" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="3.0.0" />
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="3.0.0" />
</ItemGroup>
As far as I know, IWebHostEnvironment
should be in the Microsoft.Extensions.Hosting.Abstractions
nuget package, but referencing it does not seem to work.
Does anyone have any ideas? -Thanks!
It is much easier to add a service to an API project. That's just one extra line.
If you can't or don't want to start over, change your project manually. Forget about IWebHostBuilder
, it is now obsolete or deprecated or something.
I could post some fragments here but much easier: create a temporary API project, copy over the Program and Startup classes (but keep your namespaces) and then, inside Startup:
public void ConfigureServices(IServiceCollection services)
{
services.AddHostedService<Worker>(); // the worker will run
services.AddControllers();
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加