加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 使用Autofac注册容器本身

发布时间:2020-12-15 18:18:43 所属栏目:百科 来源:网络整理
导读:我想知道注册容器本身是否有任何副作用 IContainer container;ContainerBuilder builder = new ContainerBuilder();container = builder.Build();builder.RegisterInstance(container).AsIContainer(); 并使用它像这样 builder.RegisterTypeIManagmentServic
我想知道注册容器本身是否有任何副作用
IContainer container;
ContainerBuilder builder = new ContainerBuilder();
container = builder.Build();
builder.RegisterInstance(container).As<IContainer>();

并使用它像这样

builder.RegisterType<IManagmentServiceImp>().As<ManagmentServiceImp>()
    .WithParameter(new ResolvedParameter(
            (pi,ctx) => pi.ParameterType == typeof(IContainer) && pi.Name == "Container",(pi,ctx) => container
));

或者它是否会起作用.

解决方法

您的代码不安全,因为您在初始化之前注册了一个实例.

如果您需要访问组件内的容器(这不是一个好主意),您可以依赖具有Resolve方法的ILifetimeScope.

public class ManagmentServiceImp 
{
    public ManagmentServiceImp(ILifetimeScope scope)
    {
    }
}

ILifetimeScope在Autofac中自动注册,您无需为其添加注册.

有关详细信息,请参阅Autofac文档中的Controlling Scope and Lifetime.

顺便说一句,依赖IoC容器并不是一个好习惯.看起来你使用Service Locator反模式.如果您需要容器延迟加载依赖项,则可以使用Func< T>组合.或懒惰< T>

public class ManagmentServiceImp 
{
    public ManagmentServiceImp(Lazy<MyService> myService)
    {
        this._myService = myService; 
    }

    private readonly Lazy<MyService> _myService;
}

在这种情况下,首次访问时将创建MyService.

有关详细信息,请参阅Autofac文档中的Implicit Relationship.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读