2012-10-04 7 views
2

는 인터페이스를 고려 :등록을 중복 제거 할 수 있습니까?

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

내가이 시나리오가 작동하지 않기 때문에 다른 방법으로 이러한 트릭을 할 수 ...

답변

3

짧은 답변 : 당신이 할 수있는 '티. 긴 대답 : 이런 종류의 트릭을 수행하는 사용자 정의 컨테이너 확장을 작성할 수 있습니다.

[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 또는 지정된 인터페이스에 대한 기존의 등록을 덮어 같은 인터페이스의 등록을 잡기 위해 확장을 미세 조정해야합니다.

+0

감사합니다. 매력처럼 작동합니다! –