如何在 .NET 核心控制台通用主机中使用 Autofac?

How can I use Autofac in .NET core console generic host?

我有使用通用主机的 .NET 核心控制台应用程序。我有工人 class (ImageFileWatcher) 和额外的 class(ThumbnailProcessor) 及其接口 (IThumbnailProcessor)。我想使用 Autofac 实现来进行依赖注入,而不是通常的 DI 实现。我怎样才能做到这一点?这是我的 program.cs 代码:

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((hostContext,configBuilder) =>
            {
                configBuilder.AddEnvironmentVariables(prefix: "ImageService_");
            })
            .ConfigureServices((hostContext, services) =>
            {
                services.AddHostedService<ImageFileWatcher>();

                services.AddSingleton<IThumbnailProcessor, ThumbnailProcessor>();

                var config = hostContext.Configuration;

                services.AddOptions<ImageConfig>()
                    .Configure(imageConfig =>
                    {
                        imageConfig.CompressionLevel = 0.99M;
                    })
                    .Bind(config.GetSection(nameof(ImageConfig)));

                services.AddOptions<ImageSizeConfig>(ImageSizeConfig.Thumbnail)
                    .Configure(thumbnailSizeConfig =>
                    {
                        thumbnailSizeConfig.FilePrefix = "thumb-";
                    })
                    .Bind(config.GetSection("ImageConfig:thumbnail"));

                services.Configure<ImageSizeConfig>(ImageSizeConfig.Medium, config.GetSection("ImageConfig:medium"));
                services.Configure<ImageSizeConfig>(ImageSizeConfig.Large, config.GetSection("ImageConfig:large"));

            });

}
  1. 安装Autofac.Extensions.DependencyInjection
  2. 将此调用添加到构建主机的过程中 -> .UseServiceProviderFactory(new AutofacServiceProviderFactory())
  3. ConfigureContainer<ContainerBuilder>(...)添加到构建主机的过程中并定义您的依赖关系

a sample for this as well.