asp.net-web-api – 如何在StructureMap ServiceActivator中使用Container而不是ObjectFactory?

前端之家收集整理的这篇文章主要介绍了asp.net-web-api – 如何在StructureMap ServiceActivator中使用Container而不是ObjectFactory?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在使用StructureMap在WebAPI中实现DI时,我们使用了在中的ServiceActivator

> Configuring Dependency Injection with ASP.NET WebAPI 2.1
> WebAPI + APIController with structureMap

public class ServiceActivator : IHttpControllerActivator
{
    public ServiceActivator(HttpConfiguration configuration) {}    

    public IHttpController Create(HttpRequestMessage request,HttpControllerDescriptor controllerDescriptor,Type controllerType)
    {
        var controller = ObjectFactory.GetInstance(controllerType) as IHttpController;
        return controller;
    }
}

但现在有了新的StructureMap,我的ReSharper建议:

Class ‘StructureMap.ObjectFactory’ is obsolete: ObjectFactory will be removed in a future 4.0 release of StructureMap. Favor the usage of the Container class for future work

集装箱上的智能感觉给我的信息非常有限。

我们应该如何用Container类重写我们的ServiceActivator?

解决方法

static stuff is going away.如果不使用某种类型的服务定位器,你将不得不实现自己“的ObjectFactory”为 referenced here
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 =>
        {
               // default config
         });
     }
}

更新:我以前的答案是错误的。感谢@JoeMighty的头。

猜你在找的asp.Net相关文章