Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/280.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在Autofac模块的依赖注入中注入IHostedService_C#_.net Core_Autofac - Fatal编程技术网

C# 如何在Autofac模块的依赖注入中注入IHostedService

C# 如何在Autofac模块的依赖注入中注入IHostedService,c#,.net-core,autofac,C#,.net Core,Autofac,我正在尝试使用Autofac Di容器来构建依赖项,而不是.netcore defaultIServiceCollection。我需要注入IHostedServiceIServiceCollection有方法AddHostedService,但我在AutofacContainerBuilder中找不到替代方法 Autofac文档说明您可以从IServiceCollection中填充ContainerBuilder,因此一个解决方案是在IServiceCollection中添加IHostedSer

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

Autofac文档说明您可以从IServiceCollection中填充
ContainerBuilder
,因此一个解决方案是在IServiceCollection中添加IHostedService,然后从中填充ContainerBuilder,但我有多个AutofacModule,他们中的一些人相互注册,各自负责自己的服务,在启动时直接从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添加额外依赖项的简单扩展方法不是一个选项。

只需像这样注册它们

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

您可以在上找到源代码。

只需这样注册即可

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

您可以在上找到源代码。

只是为了澄清一下,如果我注册多个iHostedService all
autofac将创建IEnumerable,而“webhost builder”将解析并运行所有这些源代码,对吗?是,它将返回IHostedService的枚举,然后所有这些都将由web-host启动。如果我在问题开始时阅读此答案,我将节省1-2小时的时间来寻找解决方案,因为我一直在进行autofac和HostedService注册,但我在命名参数方面有问题。请澄清,如果我注册多个IHostedServices all
。因为
autofac将创建IEnumerable,“webhost builder”将解析并运行所有IHostedService,对吗?是的,它将返回IHostedService的枚举,然后所有IHostedService都将由web-host启动。如果我在问题开始时阅读此答案,由于我一直在进行autofac和HostedService注册,我本来可以节省1-2小时的时间来寻找解决方案,但我在命名参数方面遇到了问题。