我正在尝试使用Autofac Di容器来构建依赖关系,而不是.netcore default IServiceCollection。我需要注入IHostedService。IServiceCollection有方法,AddHostedService但是在Autofac中找不到替代方法ContainerBuilder。
Autofac Documentation说,您可以从中进行填充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());
}
...
...
}
Run Code Online (Sandbox Code Playgroud)
最终,我想将ParentModule包装在包中并上传到自定义的NugetServer中,这样我就可以在需要的任何地方添加ParentModule,而无需记住在IServiceCollection中注入一些服务。 …