简体   繁体   English

.NET Core Windows 服务与 Autofac

[英].NET Core Windows Service with Autofac

I've created ASP.NET Core web apps where I've used AutoFac by putting .UseServiceProviderFactory(new AutofacServiceProviderFactory()) on the Host.CreateDefaultBuilder(...)``` call as well as the following on the Startup class:我通过将.UseServiceProviderFactory(new AutofacServiceProviderFactory())放在 Host.CreateDefaultBuilder(...)``` 调用以及 Startup 类上的以下内容创建了 ASP.NET Core Web 应用程序,其中我使用了 AutoFac:

public void ConfigureContainer(ContainerBuilder builder)
{
    builder.RegisterModule<ExampleRestApiModule>();

}

I've also done it on a Console app by creating the ContainerBuilder manually then getting an instance of an App class and calling Run().我还在控制台应用程序上通过手动创建 ContainerBuilder 然后获取 App 类的实例并调用 Run() 来完成此操作。 I'm writing a Windows Service in .NET Core 5 now and with the built in DI the template project registers a Worker class which derives from Microsoft.Extensions.Hosting.BackgroundService .我现在正在.NET Core 5 中编写一个 Windows 服务,并且使用内置的 DI,模板项目注册了一个派生自Microsoft.Extensions.Hosting.BackgroundService的 Worker 类。 There isn't a call directly in my project to the ExecuteAsync method so it's not like the standard console app where I manually get the instance to invoke.在我的项目中没有直接调用 ExecuteAsync 方法,因此它不像标准控制台应用程序那样我手动获取要调用的实例。 This is my program class:这是我的程序类:

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

    public static IHostBuilder CreateHostBuilder(string[] args)
    {
        IConfiguration configuration = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            //.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables()
            .AddCommandLine(args)
            .Build();

        return Host.CreateDefaultBuilder(args)
            .UseWindowsService(options => { options.ServiceName = "MariaDB Backup Service"; })
            .UseServiceProviderFactory(new AutofacServiceProviderFactory())
            .ConfigureServices((hostContext, services) =>
            {
                var backupServiceConfig = new List<BackupServiceConfig>();
                configuration.Bind("Tasks:BackupService", backupServiceConfig);
                services.AddSingleton(backupServiceConfig);
                
                services.AddTransient<IBackupCommandFactory, BackupCommandFactory>();
                services.AddTransient<MariaDbBackupService>();
                services.AddHostedService<BackgroundWorker>();

            })
            ;


    }
}

and I've tried putting the public void ConfigureContainer(ContainerBuilder builder) on the background worker but it's never getting called.我已经尝试将public void ConfigureContainer(ContainerBuilder builder)放在后台工作人员上,但它永远不会被调用。 Given that if this was a ASP.NET Core app the Host.CreateDefaultBuilder call would use:假设这是一个 ASP.NET Core 应用程序,则 Host.CreateDefaultBuilder 调用将使用:

.ConfigureWebHostDefaults(webBuilder =>
{
    webBuilder.UseStartup<Startup>();
});

and then something know to invoke the AutoFac ConfigureContainer method, is there an equivalent Use statement I'm supposed to put in so the platform knows to call it?然后知道调用 AutoFac ConfigureContainer 方法,是否有一个等效的 Use 语句我应该放入以便平台知道调用它? Or is there another way to do it?还是有其他方法可以做到这一点?

I want to use some more advanced IoC features within AutoFac and not sure how else to get the IServiceCollection integrated between AutoFac and MS DI.我想在 AutoFac 中使用一些更高级的 IoC 功能,但不确定如何在 AutoFac 和 MS DI 之间集成 IServiceCollection。

You need to pass the ConfigureContainer function into the call .UseServiceProviderFactory(new AutofacServiceProviderFactory(ConfigureContainer)) or you can add an additional call .ConfigureContainer<ContainerBuilder>(ConfigureContainer)您需要将ConfigureContainer函数传递给调用.UseServiceProviderFactory(new AutofacServiceProviderFactory(ConfigureContainer))或者您可以添加一个额外的调用.ConfigureContainer<ContainerBuilder>(ConfigureContainer)

We have a sample for this here as well .我们在这里也有一个示例

I would like add code sample to @alsami first suggestion.我想将代码示例添加到@alsami 第一个建议。

 public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .UseServiceProviderFactory(new AutofacServiceProviderFactory(
                    (ContainerBuilder b) => { RegisterDependencies(b); }))
                .ConfigureServices((hostContext, services) =>
                {
                    services.AddHostedService<Worker>();
                });

        private static void RegisterDependencies(ContainerBuilder builder)
        {
            builder.RegisterModule(new MyModule());
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM