本文介绍了将Autofac与ASP.Net Core 3.1通用主机"Worker Service"一起使用应用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在ASP.Net Core应用程序中,可以使用以下命令轻松配置Autofac:
In an ASP.Net Core application, its easy to configure Autofac using:
public class Program
{
public static void Main(string[] args)
{
// ASP.NET Core 3.0+:
// The UseServiceProviderFactory call attaches the
// Autofac provider to the generic hosting mechanism.
var host = Host.CreateDefaultBuilder(args)
.UseServiceProviderFactory(new AutofacServiceProviderFactory())
.ConfigureWebHostDefaults(webHostBuilder => {
webHostBuilder
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>();
})
.Build();
host.Run();
}
}
public class Startup
{
// Omitting extra stuff so you can see the important part...
public void ConfigureServices(IServiceCollection services)
{
// Add controllers as services so they'll be resolved.
services.AddMvc().AddControllersAsServices();
}
public void ConfigureContainer(ContainerBuilder builder)
{
// If you want to set up a controller for, say, property injection
// you can override the controller registration after populating services.
builder.RegisterType<MyController>().PropertiesAutowired();
}
}
但是在通用主机中, Worker类没有对ConfigureServices
和ConfigureContainer
的任何内置支持.
But in a generic host, the Worker class does not have any built in support for ConfigureServices
and ConfigureContainer
.
如何在非ASP.Net Core应用程序中为通用主机启用相同的功能?
How do I enable the same for a generic host in a non ASP.Net Core application?
推荐答案
通用主机生成器确实具有对ConfigureContainer
和ConfigureServices
var host = Host.CreateDefaultBuilder(args)
.UseServiceProviderFactory(new AutofacServiceProviderFactory())
.ConfigureContainer<ContainerBuilder>(builder => {
builder.RegisterType<MyDependencyType>();
//...
})
.ConfigureServices(services => {
services.AddHostedService<Worker>();
//...
})
.Build();
host.Run();
参考 .NET通用主机
这篇关于将Autofac与ASP.Net Core 3.1通用主机"Worker Service"一起使用应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!