是否可以从 Autofac 容器构建器中删除现有注册? [英] Is it possible to remove an existing registration from Autofac container builder?

查看:33
本文介绍了是否可以从 Autofac 容器构建器中删除现有注册?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

类似的东西:

builder.RegisterType<MyType>().As<IType>();
builder.RegisterType<MyType2>().As<IType>();
builder.DeRegisterType<MyType>().As<IType>()

var container = builder.Build();
var types = container.Resolve<IEnumerable<IType>>();
Assert.IsTrue(types.Count == 1);
Assert.IsTrue(types[0].GetType == typeof(MyType2));

场景:我经历了一堆程序集,然后我注册了类型,但我想确保我只有一个给定类型的实现.我需要在创建容器之前执行此操作.我可以自己跟踪,但如果 Autofac 能帮我一点,那就太好了.

Scenario: I go through bunch of assemblies and as I go I register types but I want to make sure that I have only one implementation of a given type. I need to do this before I create the container. I could track that on my own but it would be nice if Autofac could help me a bit.

推荐答案

这不能直接使用 ContainerBuilder 来完成,除非您从新开始.请注意,首先构建了一个容器,您应该能够构建一个新容器过滤掉不需要的类型并重用第一个容器的注册.像这样:

This cannot be done directly using the ContainerBuilder, unless you start over with a new one. Mind you, having first built a container you should be able to construct a new container filtering away unwanted types and reusing the registrations from the first container. Like this:

...
var container = builder.Build();

builder = new ContainerBuilder();
var components = container.ComponentRegistry.Registrations
                    .Where(cr => cr.Activator.LimitType != typeof(LifetimeScope))
                    .Where(cr => cr.Activator.LimitType != typeof(MyType));
foreach (var c in components)
{
    builder.RegisterComponent(c);
}

foreach (var source in container.ComponentRegistry.Sources)
{
    cb.RegisterSource(source);
}

container = builder.Build();

这不是很优雅,但它有效.现在,如果您能详细说明为什么要这样做,也许有更好的方法.

This is hardly very elegant but it works. Now, if you could elaborate on why you want to do this, perhaps there is a better way.

这篇关于是否可以从 Autofac 容器构建器中删除现有注册?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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