2016-04-20 32 views

回答

2

傳統上你會使用StructureMap的ObjectFactory.GetInstance<T>來解決你的靜態方法的依賴性。不過,由於使用它會將代碼緊密耦合到IoC容器(請參閱服務定位器反模式上的this post),因此它一直被棄用。

下一個最好的方法是創建一個返回的IContainer實例的ObjectFactory,類似這樣的自己的靜態等效:

public static class ObjectFactory 
{ 
    private static readonly Lazy<Container> _containerBuilder = new Lazy<Container>(defaultContainer, LazyThreadSafetyMode.ExecutionAndPublication); 

    public static IContainer Container 
    { 
     get { return _containerBuilder.Value; } 
    } 

    private static Container defaultContainer() 
    { 
      return new Container(x => { 
       x.AddRegistry(new YourRegistry()) }; 
      }); 
    } 
} 

this後進行了較深入實施。

+0

我目前正在執行此解決方案。一旦我確認它有效,我會接受答案。謝謝! – jkruer01

+0

沒問題。你有沒有設法讓它工作?樂意效勞。 –

相關問題