使用Autofac注册容器本身

Sca*_*net 10 c# ioc-container inversion-of-control autofac

我想知道注册容器本身是否有任何副作用

IContainer container;
ContainerBuilder builder = new ContainerBuilder();
container = builder.Build();
builder.RegisterInstance(container).As<IContainer>();
Run Code Online (Sandbox Code Playgroud)

并使用它像这样

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

或者它是否会起作用.

Cyr*_*and 26

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

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

public class ManagmentServiceImp 
{
    public ManagmentServiceImp(ILifetimeScope scope)
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

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

有关详细信息,请参阅从Autofac文档控制范围和生命周期.

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

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

    private readonly Lazy<MyService> _myService;
}
Run Code Online (Sandbox Code Playgroud)

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

隐关系Autofac文档的详细信息.


tor*_*vin 11

您可以使用此扩展方法:

public static void RegisterSelf(this ContainerBuilder builder)
{
    IContainer container = null;
    builder.Register(c => container).AsSelf();
    builder.RegisterBuildCallback(c => container = c);
}
Run Code Online (Sandbox Code Playgroud)

像这样用它: builder.RegisterSelf();

  • `IContainer` 继承自 `ILifetimeScope` 所以铸造我的工作...... (2认同)