What is the difference between DependencyResolver.SetResolver and HttpConfiguration.DependencyResolver in WebAPI

感情迁移 提交于 2019-11-27 11:27:20

Prevent mixing MVC and Web API in the same project. Microsoft seems to suggest this, because the Visual Studio template for Web API mixes the project automatically with MVC, but this is a bad idea.

From an architectural point of view, MVC and Web API are completely different. MVC is a UI technology aimed to optimize end user experience. Web API is a web service technology that is aimed to optimize the experience for the (client) developer.

MVC and Web API don't share any presentation specific code. Mixing them in the same project just makes that project bigger and more complicated.

But perhaps even more importantly, both application types have their own DI configuration needs. They have their own Composition Root and mixing that into a single DI configuration (a single DI container) can make your configuration extraordinary hard.

And last, mixing Web API with MVC in the same project leads to painful ambiguous naming conflicts, since Web API assemblies contains a lot of classes that share the exact same name as MVC counterparts (but with slightly different implementations).

I guess you mixed up between MVC and Web API:

DependencyResolver.SetResolver

is for MVC and belongs to assembly System.Web.Mvc. Otherwise:

Configuration.DependencyResolver

for Web APi, it belongs to assembly System.Web.Http.

So, in your project, it uses both MVC and Web Api, that is why you see two lines to configure IoC for each

DependencyResolver.SetResolver is an MVC construct and is required to support IOC using MVC.

The GlobalConfiguration.Configuration.DependencyResolver is WebApi specific.

You you will only need both if you want to support both MVC and WebApi within the same project.

It is may also be worth pointing out that you do not normally need to explicitly set the DependencyResolver.SetResolver as the Ninject Mvc3 has a bootstrap for this... see here

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