相关疑难解决方法(0)

使用ASP.NET Web API 2.1配置依赖项注入

我正在创建一个ASP.NET Web API 2.1站点,因为我想将依赖项直接注入控制器,所以我创建了自己的IDependencyResolver实现,以便StructureMap为我处理.

public class StructureMapDependencyResolver : IDependencyResolver
{
    public IDependencyScope BeginScope()
    {
        return this;
    }

    public object GetService(Type serviceType)
    {
        return ObjectFactory.GetInstance(serviceType);
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {            
        return ObjectFactory.GetAllInstances(serviceType).Cast<object>();
    }

    public void Dispose()
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,我通过将此行添加到Global.asax中的Application_Start方法,告诉Web API使用此类

GlobalConfiguration.Configuration.DependencyResolver = new StructureMapDependencyResolver();
Run Code Online (Sandbox Code Playgroud)

编译,但当我尝试访问浏览器中的任何API方法时,我得到了这样的错误

No Default Instance defined for PluginFamily System.Web.Http.Hosting.IHostBufferPolicySelector, System.Web.Http
Run Code Online (Sandbox Code Playgroud)

当我在StructureMap配置中添加一行时,那个相对容易解决

this.For<IHostBufferPolicySelector>().Use<WebHostBufferPolicySelector>();
Run Code Online (Sandbox Code Playgroud)

然而,我得到了其他System.Web.Http类的其他类似错误,虽然我可以解决其中的一些,但我仍然坚持如何处理其中的3个,即ITraceManager,IExceptionHandler和IContentNegotiator.

问题是TraceManager似乎是ITraceManager的默认实现,是一个内部类,所以我不能在我的StructureMap配置中引用它.

那么我是以完全错误的方式进行此操作还是有其他方法来注入这些内部类?

structuremap asp.net dependency-injection asp.net-web-api

29
推荐指数
1
解决办法
3万
查看次数