c# - 是否可以从 Autofac 容器构建器中删除现有注册?

标签 c# 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 能帮我一点忙就好了。

最佳答案

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

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

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

关于c# - 是否可以从 Autofac 容器构建器中删除现有注册?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5091101/

相关文章:

c# - Hololens/Unity : recognizing the difference between Navigation and Manipulation Gestures

c# - 为什么 C# 7.2 中的 Pinnable<T> 类是这样定义的?

c# - 使用 .NET 将 HTML 转换为 PDF 文件的免费工具

c# - RSA 在 C# (.NET 3.5) 中解密数据,在 php 5.3.2 中用 openssl 加密

C#:如何在按下鼠标左/右键时获取鼠标的坐标?

c# - .Register 和 .RegisterType 是否等效(对于具有无参数构造函数的类)?

autofac - 使用 Autofac 注册带有参数的具体类型为 null

asp.net-mvc-3 - 如何创建需要使用 autofac 进行注入(inject)的 Quartz.NET 作业

c# - 一段时间后在 RabbitMQ 中获取 OutOfMemory

c# - 如何在 Nunit Framework 的 Autofac 容器中更新已注册类的属性