是否有可能配置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

查看:127
本文介绍了是否有可能配置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和网络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和网页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);

也可以共享之间注册两个,因为 InstancePerApiRequest InstancePerHtt prequest 终身范围现在共享相同的标签。

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

请注意,对于设置依赖解析器对网页API和MVC的机理是不同的。网络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天全站免登陆