0
我有一個WebApi解決方案,我正在使用StructureMap.WebApi2用於依賴注入的Nuget包。如何從Web API 2中的靜態類使用StructureMap?
我想用Fody Tracer來編織跟蹤方法。我是implementing my own custom log adapter,它要求我從靜態類/方法返回記錄器的實例。
什麼是我使用結構圖從靜態類/方法獲取我的記錄器實例的正確方法?
我有一個WebApi解決方案,我正在使用StructureMap.WebApi2用於依賴注入的Nuget包。如何從Web API 2中的靜態類使用StructureMap?
我想用Fody Tracer來編織跟蹤方法。我是implementing my own custom log adapter,它要求我從靜態類/方法返回記錄器的實例。
什麼是我使用結構圖從靜態類/方法獲取我的記錄器實例的正確方法?
傳統上你會使用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後進行了較深入實施。
我目前正在執行此解決方案。一旦我確認它有效,我會接受答案。謝謝! – jkruer01
沒問題。你有沒有設法讓它工作?樂意效勞。 –