如何从Autofac模块的依赖注入中注入IHostedService

时间:2019-05-07 10:20:30

标签: c# .net-core autofac

我正在尝试使用Autofac Di容器来构建依赖关系,而不是.netcore默认IServiceCollection。我需要注入IHostedServiceIServiceCollection有方法AddHostedService,但是在Autofac ContainerBuilder中找不到替代方法。

Autofac文档说,您可以从ContainerBuilder填充IServiceCollection,所以一种解决方案是在IServiceCollection中添加IHostedService,然后从中填充ContainerBuilder,但是我有多个AutofacModule,其中有些相互注册,他们每个人都有自己的服务责任,并且在Startup中直接从ChildModule注入一些服务似乎不正确。

 public class ParentModule : Module
 {
    protected override void Load(ContainerBuilder builder)
    {
       builder.RegisterModule(new ChildModule());
    }
 }

 public class ChildModule : Module
 {
    protected override void Load(ContainerBuilder builder)
    {
       //TODO Add hosted service here.
    }
 }

 public class Startup
 {
   ...
   ...
   public IServiceProvider ConfigureServices(IServiceCollection services)
   {
      var container = new ContainerBuilder();
      container.RegisterModule(new ParentModule());

      return new AutofacServiceProvider(container.Build());
   }
   ...
   ...
 }

最终,我想将ParentModule打包在包中,然后将其上传到自定义的NugetServer中,这样我就可以在需要的任何地方添加ParentModule,而无需记住在IServiceCollection中注入一些服务。

我的模块非常复杂,并且具有多个层次的深度,因此无法选择IServiceCollection的简单扩展方法来添加其他依赖项。

1 个答案:

答案 0 :(得分:4)

只需这样注册他们

builder.Register<MyHostedService>()
       .As<IHostedService>()
       .InstancePerDependency();

虚拟主机负责解决IHostedService的所有注册并运行它们。

扩展方法AddHostedService<THostedService>并没有什么不同,如您所见

public static IServiceCollection AddHostedService<THostedService>(this IServiceCollection services)
where THostedService : class, IHostedService
{
   return services.AddTransient<IHostedService, THostedService>();
}

您可以在github上找到源代码。

相关问题