0

接口依賴於相同類型的接口來完成某些特定操作。但是,當我嘗試使用統一註冊它我越來越統一自我依賴接口註冊

類型「System.StackOverflowException」未處理的異常 發生在Microsoft.Practices.Unity.DLL

我覺得它落入一個一種自我參考循環並填充內存。

我的方法有問題嗎? 我該如何解決它?

我有這樣的接口;

public interface IEnvironment 
{ 
    string RootUrl { get; set; } 
    string ImagesPath { get; set; } 
    IEnvironment DependentEnvironment { get; set; } 
} 

這是我的代碼的運行環境,如本地主機,生產的Windows Phone模擬器等..表示

我有兩個班,現在實現這個權利;

class Localhost : IEnvironment 
{ 
    public string RootUrl { get; set; } 
    public string ImagesPath { get; set; } 
    public IEnvironment DependentEnvironment { get; set; } 

    public Localhost(IEnvironment dependentEnvironment) 
    { 
     ImagesPath = "images"; 
     DependentEnvironment = dependentEnvironment; 
    } 
} 

public class WindowsPhoneSimulator : IEnvironment 
    { 
     public string RootUrl { get; set; } 
     public string ImagesPath { get; set; } 
     public IEnvironment DependentEnvironment { get; set; } 
     public WindowsPhoneSimulator(IEnvironment dependentEnvironment) 
     { 
      ImagesPath = "/Assets/images"; 
      DependentEnvironment = dependentEnvironment; 
     } 
    } 

這樣一個環境可以依賴另一個呢?爲什麼?因爲例如WindowsPhoneSimulator可以對本地主機進行api調用,所以當我部署應用程序時,我會將注入更改爲ProductionEnvironment。所以它應該知道要調用哪個環境。

當我開始解決我的對象時,問題就開始了;

IocContainer.RegisterType<IEnvironment, WindowsPhoneSimulator>(); 

有什麼建議嗎?

+1

你可能想用'RegisterInstance'和手動'Resolve''依賴的環境來註冊所有環境作爲命名實例...也許你需要使用子容器。你應該考慮當解析()時應該發生什麼 - Unity不能神奇地發現你想要的結果(我不確定是基於你的問題),所以需要一些澄清(也許名稱爲'Resolve (「Phone」)')。 – 2014-10-20 05:47:56

回答

2

你沒有顯示你是如何註冊你的類型,但大概你只是用一個標準的RegisterType方法註冊它們。當你註冊第二個類型時,它會覆蓋第一個類型,所以Unity只知道你的一個類(其次是註冊的類)。那麼爲什麼你會得到一個堆棧溢出異常是有意義的,因爲它試圖創建一個say,WindowsPhoneSimulator類的實例以傳遞到WindowsPhoneSimulator類......這顯然不能做到。

相反,您需要將統一類型註冊爲「命名類型」,然後當您想使用其中一個類時,在解析類時創建依賴覆蓋,告訴Unity要使用哪一個。然後

container.RegisterType<IEnvironment, Localhost>("Localhost") 
container.RegisterType<IEnvironment, WindowsPhoneSimulator>("WindowsPhoneSimulator") 

當你要創建的類型,像這樣:

因此,註冊類型爲命名類型

DependencyOverride dep = new DependencyOverride(typeof(IEnvironment) 
         , container.Resolve<IEnvironment>("Localhost")); 

IEnvironment obj2 = container.Resolve<IEnvironment>("WindowsPhoneSimulator", dep); 

在上面的例子中,你首先解決Localhost類的實例,然後使用該實例創建dependencyOverride,並將其傳遞給WindowsPhoneSimulator類的構造函數。因此,WindowsPhoneSimulator在構建時會傳遞Localhost的實例。

+0

命名實例和DependencyOverride我在找什麼。我還沒有測試過,但我從你的例子中看到的邏輯完全合理。 – 2014-10-24 14:20:39