如何配置Web API 2和结构图

问题描述 投票:0回答:2

我浏览了多个博客等,试图找出如何使用 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;
        }
    }
}
asp.net-web-api structuremap asp.net-web-api2
2个回答
19
投票

我试图解释如何一起使用(轻松) 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));
    ...

5
投票

有一个核心: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>();
        });

        ...
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.