Using WebApi and structure map dependency injection

≯℡__Kan透↙ 提交于 2019-12-06 08:48:46

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

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);
}

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/

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