如何在 Web API 2 中使用来自静态 Class 的 StructureMap?
How to Use StructureMap From A Static Class in Web API 2?
我有一个 WebApi 解决方案,我正在使用 StructureMap.WebApi2 用于依赖注入的 Nuget 包。
我想使用 Fody Tracer to weave in trace methods. I am implementing my own custom log adapter,这需要我从静态 class/method return 我的记录器实例。
我使用 Structure Map 从静态 class/method 获取记录器实例的正确方法是什么?
传统上,您会使用 StructureMap 的 ObjectFactory.GetInstance<T>
来解析静态方法的依赖关系。然而,这已被弃用,因为它通常不受欢迎,因为使用它会将您的代码紧密耦合到 IoC 容器(请参阅 this post 服务定位器反模式)。
下一个最佳方法是创建您自己的 ObjectFactory 的静态等价物,returns 一个 IContainer 实例,类似于:
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 post。
我有一个 WebApi 解决方案,我正在使用 StructureMap.WebApi2 用于依赖注入的 Nuget 包。
我想使用 Fody Tracer to weave in trace methods. I am implementing my own custom log adapter,这需要我从静态 class/method return 我的记录器实例。
我使用 Structure Map 从静态 class/method 获取记录器实例的正确方法是什么?
传统上,您会使用 StructureMap 的 ObjectFactory.GetInstance<T>
来解析静态方法的依赖关系。然而,这已被弃用,因为它通常不受欢迎,因为使用它会将您的代码紧密耦合到 IoC 容器(请参阅 this post 服务定位器反模式)。
下一个最佳方法是创建您自己的 ObjectFactory 的静态等价物,returns 一个 IContainer 实例,类似于:
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 post。