WebAPI中的DependencyResolver.SetResolver和HttpConfiguration.DependencyResolver有什么区别 [英] What is the difference between DependencyResolver.SetResolver and HttpConfiguration.DependencyResolver in WebAPI

查看:137
本文介绍了WebAPI中的DependencyResolver.SetResolver和HttpConfiguration.DependencyResolver有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个现有项目,该项目使用AutoFac作为IoC.

在注册码中,我有以下几行:

var resolver = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(resolver));
config.DependencyResolver = new AutofacWebApiDependencyResolver(resolver);

所以我的问题是DependencyResolver.SetResolverHttpConfiguration.DependecyResolver有什么区别?我为什么要分配它们两个?

解决方案

防止在同一项目中混合MVC和Web API. Microsoft似乎建议这样做,因为Web API的Visual Studio模板会自动将项目与MVC混合在一起,但这不是一个好主意.

从体系结构的角度来看,MVC和Web API完全不同. MVC是旨在优化最终用户体验的UI技术. Web API是一种Web服务技术,旨在为(客户端)开发人员优化体验.

MVC和Web API不共享任何特定于演示的代码.将它们混合在同一个项目中只会使该项目变得更大,更复杂.

但也许更重要的是,两种应用程序类型都有自己的DI配置需求.他们有自己的合成根,并将其混合到单个DI配置中(一个DI容器)会使您的配置异常困难.

最后,在同一项目中将Web API与MVC混合会导致痛苦的模棱两可的命名冲突,因为Web API程序集包含许多类,它们的名称与MVC对应的名称完全相同(但实现方式略有不同).

I have existing project, which uses AutoFac as IoC.

In the registration code i have these lines:

var resolver = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(resolver));
config.DependencyResolver = new AutofacWebApiDependencyResolver(resolver);

So my question is what is the difference between DependencyResolver.SetResolver and HttpConfiguration.DependecyResolver? Why should I assign both of them?

解决方案

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).

这篇关于WebAPI中的DependencyResolver.SetResolver和HttpConfiguration.DependencyResolver有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆