接口依賴於相同類型的接口來完成某些特定操作。但是,當我嘗試使用統一註冊它我越來越統一自我依賴接口註冊
類型「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>();
有什麼建議嗎?
你可能想用'RegisterInstance'和手動'Resolve''依賴的環境來註冊所有環境作爲命名實例...也許你需要使用子容器。你應該考慮當解析()時應該發生什麼 - Unity不能神奇地發現你想要的結果(我不確定是基於你的問題),所以需要一些澄清(也許名稱爲'Resolve (「Phone」)')。 –
2014-10-20 05:47:56