2011-06-08 45 views
1

我已經配置像我的容器如下:團結容器對象分辨等級

container = new UnityContainer() 
      .RegisterType<IA, A>() 
      .RegisterType<IB, B>() 
      .RegisterType<IC, C>(new InjectionConstructor(strA)); 

我需要的是什麼,我要註冊其他C實例,如:

container.RegisterType<IC, C>(new InjectionConstructor(strB)); 

注STRA之間的差異STRB。

A和B需要C.但是我想使用的第一個C和B使用第二C.

是否有統一了適當的方式做到這一點?

感謝

+1

乍一看,strA和strB應該是A和B上的屬性,並傳遞給/由C評估。 – Till 2011-06-08 08:01:50

+0

我喜歡這樣。這應該是正確的方法。 – Hash 2011-06-09 01:30:44

回答

2

你會想要使用named type registration

var container = new UnityContainer() 
    .RegisterType<IC, C>("ForA", new InjectionConstructor(strA)) 
    .RegisterType<IC, C>("ForB", new InjectionConstructor(strB)) 

    .RegisterType<IA, A>(new InjectionConstructor(container.Resolve<IC>("ForA"))) 
    .RegisterType<IB, B>(new InjectionConstructor(container.Resolve<IC>("ForB"))); 
0

我已經在過去的裝潢/,以確定它們映射facading比較常見的接口來實現這一點。

// new interface just for A 
public interface ICforA : IC { } 

// new interface just for B 
public interface ICforB : IC { } 

container = new UnityContainer() 
      .RegisterType<IA, A>() 
      .RegisterType<IB, B>() 
      .RegisterType<ICforA, C>(new InjectionConstructor(strA)); 
      .RegisterType<ICforB, C>(new InjectionConstructor(strB)); 

聲明:代碼從內存寫入,而不是Visual Studio。