c# - 是否可以在创建 Autofac LifetimeScope 后向其添加注册?

标签 c# .net dependency-injection autofac lifetime-scoping

我知道您可以向 LifetimeScope 添加注册 它是这样创建的:

using(var scope = container.BeginLifetimeScope(builder =>  
    {  builder.RegisterType<Override>().As<IService>();
       builder.RegisterModule<MyModule>();
    }))
{
  // The additional registrations will be available
  // only in this lifetime scope.
}

LifetimeScope 创建后是否可以添加注册? (例如在 using block 中添加注册)

最佳答案

您可以访问 ILifetimeScopeComponentRegistry 属性,使用此对象可以注册新的 IComponentRegistration,您可以使用 创建它RegistrationBuilder 静态方法:

using(var scope = container.BeginLifetimeScope())
{
    var registration = RegistrationBuilder.ForType<ServiceA>()
                                          .As<IService>()
                                          .CreateRegistration();
    scope.ComponentRegistry.Register(registration); 

    scope.Resolve<IService>(); 
}

关于c# - 是否可以在创建 Autofac LifetimeScope 后向其添加注册?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38877510/

相关文章:

c# - 文件上传 - 返回 null

c# - 在输入 API 请求中发现未知属性时抛出错误?

c# - LINQ 从每个查询中获取第一行

c# - 不支持异常 : Could not convert constant 1 expression to string

c# - .net 标准是否像 .net Core 一样跨平台?

c# - 依赖注入(inject)——当你有很多依赖时怎么办?

c# - Ninject 的 .NET MVC3 服务定位器/依赖解析器问题

java - 使用 Roboguice 的 Android 工厂辅助注入(inject)不起作用

c# - 了解数字范围的正则表达式

c# - ASP.NET MVC : How to get route values