如何配置Web API 2和结构图

时间:2014-07-05 21:04:51

标签: asp.net-web-api structuremap asp.net-web-api2

我已经浏览过多个博客等,试图找出如何使用Web API 2配置StructureMap,但没有一个实现适合我。混淆似乎是围绕MVC使用的不同IDependency Resolver以及Web API使用的IDependency Resolver。

首先,哪个是正确的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;
        }
    }
}

2 个答案:

答案 0 :(得分:16)

链接很少,我试图解释如何一起使用(轻松) StructureMap和Web API:

我们必须实施IHttpControllerActivator,这可以从已配置的 StructureMap ObjectFactory中获利:

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;
    }
}

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

protected void Application_Start()
{
    ...
    HttpConfiguration config = GlobalConfiguration.Configuration;
    config.Services
          .Replace(typeof(IHttpControllerActivator), new ServiceActivator(config));
    ...

答案 1 :(得分:3)

这有一个难题:https://www.nuget.org/packages/WebApi.StructureMap/

public class Global : System.Web.HttpApplication
{
    protected void Application_Start(object sender, EventArgs e)
    {
        GlobalConfiguration.Configuration.UseStructureMap<Registry>();

        // Or

        GlobalConfiguration.Configuration.UseStructureMap(x =>
        {
            x.AddRegistry<Registry1>();
            x.AddRegistry<Registry2>();
        });

        ...
    }
}