Using Autofac with ASP.Net Core 3.1 generic host “Worker Service” application

两盒软妹~` 提交于 2020-08-25 04:19:08

问题


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();
  }
}

But in a generic host, the Worker class does not have any built in support for ConfigureServices and ConfigureContainer.

How do I enable the same for a generic host in a non ASP.Net Core application?


回答1:


The generic host builder does have built-in support for ConfigureContainer and ConfigureServices

var host = Host.CreateDefaultBuilder(args)
    .UseServiceProviderFactory(new AutofacServiceProviderFactory())
    .ConfigureContainer<ContainerBuilder>(builder => {

        builder.RegisterType<MyDependencyType>();

        //...
    })
    .ConfigureServices(services => {

        services.AddHostedService<Worker>();

        //...
    })
    .Build();

host.Run();

Reference .NET Generic Host



来源:https://stackoverflow.com/questions/59645123/using-autofac-with-asp-net-core-3-1-generic-host-worker-service-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!