是否可以将 Autofac 配置为与 ASP.NET MVC 和 ASP.NET Web Api 一起使用 [英] Is it possible to configure Autofac to work with ASP.NET MVC and ASP.NET Web Api

查看:25
本文介绍了是否可以将 Autofac 配置为与 ASP.NET MVC 和 ASP.NET Web Api 一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将 Autofac 配置为与 ASP .NET MVC 和 ASP .NET Web Api 一起使用.我知道依赖解析器是不同的.但是当使用记录的方法时,我只能设置一个全局解析器.

Is it possible to configure Autofac to work with ASP .NET MVC and ASP .NET Web Api. I'm aware that the dependency resolvers are different. But when using the documented approaches I can only set one global resolver.

// Set the dependency resolver implementation.
GlobalConfiguration.Configuration.DependencyResolver = resolver;

这种方法是坏主意吗?我应该将我的解决方案分成两个项目并分别处理每个项目的依赖注入吗?

Is this approach bad idea? Should I separate my solution into two projects and handle the dependency injection for each individually?

推荐答案

当然可以将 Autofac 配置为与 MVC 和 Web API 一起使用.预计这将是一个非常常见的场景.有两种独立的依赖解析器实现,因为 MVC 和 Web API 可以相互独立使用.这同样适用于 Autofac 集成.

It is certainly possible to configure Autofac to work with both MVC and Web API. This is expected to be a very common scenario. There are two separate dependency resolver implementations because MVC and Web API can be used independently of one another. The same applies for the Autofac integrations.

在同一个应用程序中同时使用 MVC 和 Web API 时,每个应用程序都需要自己的依赖项解析器,尽管它们可以与容器的相同实例一起提供.

When using both MVC and Web API in the same application each will require its own dependency resolver, though they can be provided with the same instance of the container.

var builder = new ContainerBuilder();

// Add your registrations

var container = builder.Build();

// Set the dependency resolver for Web API.
var webApiResolver = new AutofacWebApiDependencyResolver(container);
GlobalConfiguration.Configuration.DependencyResolver = webApiResolver;

// Set the dependency resolver for MVC.
var mvcResolver = new AutofacDependencyResolver(container);
DependencyResolver.SetResolver(mvcResolver);

也可以在两者之间共享注册,因为 InstancePerApiRequestInstancePerHttpRequest 生命周期范围现在共享相同的标签.

It is also possible to share registrations between the two because the InstancePerApiRequest and InstancePerHttpRequest lifetime scopes now share the same tag.

注意设置Web API和MVC的依赖解析器的机制是不同的.Web API 使用 GlobalConfiguration.Configuration.DependencyResolver,MVC 使用 DependencyResolver.SetResolver.

Note that the mechanism for setting the dependency resolver for Web API and MVC is different. Web API uses GlobalConfiguration.Configuration.DependencyResolver and MVC uses DependencyResolver.SetResolver.

这篇关于是否可以将 Autofac 配置为与 ASP.NET MVC 和 ASP.NET Web Api 一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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