使用Autofac自行注册容器 [英] Register Container Itself Using Autofac

查看:272
本文介绍了使用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)
    {
    }
}

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

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容器不是一个好习惯.看来您使用的是服务定位器反模式.如果您需要容器延迟加载依赖项,则可以将composition与Func<T>Lazy<T>

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天全站免登陆