是否可以一次性重复注册? [英] Is it possible to deduplicate registration in unity?
问题描述
考虑接口:
public interface IOne{}
public interface ITwo{}
public interface IBoth : IOne, ITwo{}
和课
public class Both : IBoth{}
但是我需要解决基础接口,我需要在容器中注册两个接口
But when I need to resolve base interfaces I need to register both interfaces in container
<register type="IOne" MapTo="Both"/>
<register type="ITwo" MapTo="Both"/>
问题是 - 我可以这样重复数据删除注册:
The question is - can I deduplicate the registration in a way like this:
<register type="IBoth" MapTo="Both"/>
但是在不同的界面中解决它:
But resolve it in different places from different interfaces:
var o = containet.Resolve<IOne>();
var t = containet.Resolve<ITwo>();
我可以以任何其他方式做这样的技巧,因为这种情况不起作用吗? / p>
Can I do such a trick in any other way since this scenario is not working?...
推荐答案
简短的答案:你不能。
长回答:你可以写一个自定义的容器扩展,为你做这样的技巧。
Short answer: You can't. Long answer: You can write a custom container extension that does this kind of trick for you.
[TestMethod]
public void TestMethod1()
{
var container = new UnityContainer().AddNewExtension<DeduplicateRegistrations>();
container.RegisterType<IBoth, Both>();
IThree three = container.Resolve<IThree>();
Assert.AreEqual("3", three.Three());
}
public class DeduplicateRegistrations : UnityContainerExtension
{
protected override void Initialize()
{
this.Context.Registering += OnRegistering;
}
private void OnRegistering(object sender, RegisterEventArgs e)
{
if (e.TypeFrom.IsInterface)
{
Type[] interfaces = e.TypeFrom.GetInterfaces();
foreach (var @interface in interfaces)
{
this.Context.RegisterNamedType(@interface, null);
if (e.TypeFrom.IsGenericTypeDefinition && e.TypeTo.IsGenericTypeDefinition)
{
this.Context.Policies.Set<IBuildKeyMappingPolicy>(
new GenericTypeBuildKeyMappingPolicy(new NamedTypeBuildKey(e.TypeTo)),
new NamedTypeBuildKey(@interface, null));
}
else
{
this.Context.Policies.Set<IBuildKeyMappingPolicy>(
new BuildKeyMappingPolicy(new NamedTypeBuildKey(e.TypeTo)),
new NamedTypeBuildKey(@interface, null));
}
}
}
}
}
public class Both : IBoth
{
public string One() { return "1"; }
public string Two() { return "2"; }
public string Three() { return "3"; }
}
public interface IOne : IThree
{
string One();
}
public interface IThree
{
string Three();
}
public interface ITwo
{
string Two();
}
public interface IBoth : IOne, ITwo
{
}
您需要微调扩展名才能捕获注册接口,例如 IDisposable
或覆盖给定接口已经存在的注册。
You will need to fine-tune the extension in order to catch registration of interfaces like IDisposable
or overwriting an already existing registration for a given interface.
这篇关于是否可以一次性重复注册?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!