使用 Autofac 注册容器本身 [英] Register Container Itself Using Autofac

查看:35
本文介绍了使用 Autofac 注册容器本身的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在其自身内注册容器是否有任何副作用

I was wondering is there's any side effect to registering the container within itself

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
));

或者它是否会起作用.

推荐答案

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

Your code is not safe because you register an instance before it has been initialized.

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

If you need to have access to the container inside a component (which is not a good idea) you can have a dependency on ILifetimeScope which have Resolve methods.

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

ILifetimeScopeAutofac 中自动注册,您无需为其添加注册.

ILifetimeScope is automatically registered within Autofac you don't need to add registration for it.

请参阅 Autofac 文档中的控制范围和生命周期想要查询更多的信息.

See Controlling Scope and Lifetime from Autofac documentation for more information.

顺便说一句,依赖你的 IoC 容器并不是一个好习惯.看起来您使用了 Service Locator 反模式.如果你需要容器​​延迟加载依赖,你可以使用 FuncLazy

By the way, it is not a good practice to have dependency on your IoC container. It looks like you use Service Locator anti-pattern. If you need the container to lazy load dependency, you can use composition with Func<T> or Lazy<T>

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

    private readonly Lazy<MyService> _myService;
}

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

In this case, MyService will be created when you first access it.

参见 Autofac隐式关系> 文档以获取更多信息.

See Implicit Relationship from the Autofac documentation for more information.

这篇关于使用 Autofac 注册容器本身的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆