Using WebApi and structure map dependency injection

主宰稳场 提交于 2019-12-07 18:52:06

问题


Although there are so many question on stack overflow which tends similar to my this question but no one is resolving my problem

I was using an MVC4 internet application wherein i had few MVC controller and for dependency injection i was using Structure map. Although dependency injection works fine with MVC controller but when i added an WebApi controller in the same MVC internet application and using the same parameter in constructor of WebApi controller as what i am using in MVC controller but dependency injection is not working with WebApi controller, although if i don't use dependency injection for WebApi controller(parameterless constructor), then it works fine, but for WebApi dependency injection(parameterized constructor) it is throwing an error No parameter less constructor is found.

Conclusion depedencies are not being injected for WebApi Controller in Internet(MVC application).

Few articles suggested to use DependencyResolver.SetResolver(). i used but did not resolve the issue.


回答1:


The reason why WebApi controller were not working is as following:

Since MVC Controller uses different DependenyResolver instance that is the part of System.Web.MVC .dll and within the System.Web.MVC namespace

http://msdn.microsoft.com/en-us/library/system.web.mvc.idependencyresolver(v=vs.98).aspx

Where as Api Controllers uses DependencyResolver instance that is part of System.Web.Http.

http://msdn.microsoft.com/en-us/library/system.web.http.dependencies.idependencyresolver(v=vs.108).aspx




回答2:


MVC and WebAPI controllers have a different way of setting their dependency resolver. This is how I set my dependency resolver for Unity:

public void ConfigureForMvc4()
{
    DependencyResolver.SetResolver(
        new UnityMvc4.UnityDependencyResolver(Container));
}

public void ConfigureForWebApi()
{
    GlobalConfiguration.Configuration.DependencyResolver =
        new UnityWebApi.UnityDependencyResolver(Container);
}



回答3:


You need to add Dependency Injection files for WebApi

Install NuGet StructureMap.WebApi2 and in the App_Start/WebApiConfig.cs file, call StructuremapWebApi.Start();

Refer: https://www.exceptionnotfound.net/setting-up-dependency-injection-in-web-api-with-structuremap/



来源:https://stackoverflow.com/questions/15497355/using-webapi-and-structure-map-dependency-injection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!