我浏览了多个博客等,试图找出如何使用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)); ...