考虑接口:
public interface IOne{}
public interface ITwo{}
public interface IBoth : IOne, ITwo{}和类
public class Both : IBoth{}但是当我需要解析基接口时,我需要在容器中注册这两个接口
<register type="IOne" MapTo="Both"/>
<register type="ITwo" MapTo="Both"/>问题是-我是否可以像这样对注册进行重复数据删除:
<register type="IBoth" MapTo="Both"/>而是从不同的接口在不同的地方解决它:
var o = containet.Resolve<IOne>();
var t = containet.Resolve<ITwo>();既然这个场景不起作用,我可以用任何其他方式来做这样的戏法吗?
发布于 2012-10-04 18:08:02
简短的回答是:你不能。长期的回答是:你可以编写一个定制的容器扩展来为你做这类事情。
[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之类的接口注册,或者覆盖给定接口的现有注册。
https://stackoverflow.com/questions/12723867
复制相似问题