本文介绍了依赖注入与ASP.NET的Web API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在我的ASP.NET Web API控制器使用DI。显然有几个实现在那里。我只是想知道这些(城堡,Ninject,团结等等)这将是最容易配置/与ASP.NET的Web API结合保持?我得到这个错误:
If I add an empty constructor, then the constructor with IFilter
is ignored.
This is my controller:
public class ImportJsonController : ApiController
{
private readonly IFilter _filter;
public ImportJsonController(IFilter filter)
{
_filter = filter;
}
public HttpResponseMessage Post([FromBody]dynamic value)
{
//do something
return response;
}
}
解决方案
You don't need a DI Container for this. Here's how to do it by hand:
public class PoorMansCompositionRoot : IHttpControllerActivator
{
public IHttpController Create(
HttpRequestMessage request,
HttpControllerDescriptor controllerDescriptor,
Type controllerType)
{
if (controllerType == typeof(ImportJsonController))
return new ImportJsonController(new MyFilter());
return null;
}
}
You need to tell ASP.NET Web API about this class (e.g. in your Global.asax):
GlobalConfiguration.Configuration.Services.Replace(
typeof(IHttpControllerActivator),
new PoorMansCompositionRoot());
You can read about all the details here: http://blog.ploeh.dk/2012/09/28/DependencyInjectionandLifetimeManagementwithASP.NETWebAPI
这篇关于依赖注入与ASP.NET的Web API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!