asp.net-web-api – 如何配置Web API 2和结构图

前端之家收集整理的这篇文章主要介绍了asp.net-web-api – 如何配置Web API 2和结构图前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我浏览了多个博客等,试图找出如何使用Web API 2配置StructureMap,并且没有一个实现对我有用.混乱似乎在于MVC使用的不同的IDependency Resolver,以及Web API使用的.

首先,哪个是正确的Nuget包,其次,你如何使用纯Web API 2项目进行配置?

谢谢

这是我到目前为止,似乎是有效的.它是否正确?

public class StructureMapControllerActivator : IHttpControllerActivator
{
    private readonly IContainer _container;

    public StructureMapControllerActivator(IContainer container)
    {
        if (container == null) throw new ArgumentNullException("container");
        _container = container;
    }

    public IHttpController Create(HttpRequestMessage request,HttpControllerDescriptor controllerDescriptor,Type controllerType)
    {
        try
        {
            var scopedContainer = _container.GetNestedContainer();
            scopedContainer.Inject(typeof(HttpRequestMessage),request);
            request.RegisterForDispose(scopedContainer);
            return (IHttpController)scopedContainer.GetInstance(controllerType);
        }
        catch (Exception e)
        {
            // TODO : Logging
            throw e;
        }
    }
}

解决方法

有几个链接,我试图解释我们如何使用(轻松)StructureMap和Web API:

> WebAPI + APIController with structureMap
> Configuring dependency injection with ASP.NET Web API 2.1

我们必须实现IHttpControllerActivator,它可以从已经配置的StructureMap ObjectFactory中获益:

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

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

然后,我们必须注册我们的实现(global.asax):

protected void Application_Start()
{
    ...
    HttpConfiguration config = GlobalConfiguration.Configuration;
    config.Services
          .Replace(typeof(IHttpControllerActivator),new ServiceActivator(config));
    ...
原文链接:https://www.f2er.com/aspnet/249485.html

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