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

ami*_*ani 0 c# autofac .net-core

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

Autofac Documentation说,您可以从中进行填充ContainerBuilderIServiceCollection因此,一种解决方案是在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());
   }
   ...
   ...
 }
Run Code Online (Sandbox Code Playgroud)

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

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

als*_*ami 5

像这样注册他们

builder.Register<MyHostedService>()
       .As<IHostedService>()
       .InstancePerDependency();
Run Code Online (Sandbox Code Playgroud)

主机(网络主机或常规主机)负责解决所有这些注册IHostedService并运行它们。

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

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

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

  • 值得一提的是,它不再是瞬态依赖,而是单例。你可以检查答案中的github链接,它已经改变了。 (2认同)