转:autofac在mvc和webapi集成的做法
本文转自:http://www.cnblogs.com/Hai--D/p/5992573.html
var builder = new ContainerBuilder(); // Mvc Register
builder.RegisterControllers(Assembly.GetExecutingAssembly()).AsSelf().PropertiesAutowired();
builder.RegisterFilterProvider();
builder.RegisterType<UserService>().As<IUserService>().InstancePerLifetimeScope(); //WebApi Register
builder.RegisterApiControllers(Assembly.GetExecutingAssembly()).AsSelf().PropertiesAutowired();
builder.RegisterWebApiFilterProvider(GlobalConfiguration.Configuration);
builder.RegisterWebApiModelBinderProvider(); 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 resolver = new AutofacDependencyResolver(container);
DependencyResolver.SetResolver(resolver);
在实际Controller和ApiController中通过构造函数注入,这不必多说。
但是,在实际项目需求的时候,有些地方不方便使用构造函数,或者说就要使用服务定位IContainer.Resolve(ServiceType)的方式来获得服务的实例。
曾经在项目中看到过有人通过把Container设区全局静态变量来获得对象容器。这个方式在Local的情况下,不会有太大问题。在Mvc中,容器DependencyResolver.Current本身也是通过尽量变量来实现的。
public class DependencyResolver
{
public DependencyResolver(); public static IDependencyResolver Current { get; }
...
}
但是和C端不同的是,Web服务是基于请求的,autofac内部的InstancePerLifetimeScope,InstancePerHttpRequest,InstancePerApiRequest等都是基于每次请求的Scope,而静态的Container明显生命周期不符合。
所以我们写代码的时候都是通过DependencyResolver.Current.GetService()和GlobalConfiguration.Configuration.DependencyResolver.GetService()来分别获取Mvc和WebApi的对象。那么问题来了,我有一段业务逻辑在BLL中,Mvc和WebApi可以都调用到,其中需要Resolve一个服务,那么如何来指定容器呢?
带着问题,我们先来看看DependencyResolver.Current和GlobalConfiguration.Configuration.DependencyResolver,通过一组实验来对比一下:
public class WebApiApplication : System.Web.HttpApplication
{
public static System.Web.Mvc.IDependencyResolver mvcResolver;
public static System.Web.Http.Dependencies.IDependencyResolver apiResolver; protected void Application_Start()
{
...
builder.RegisterType<UserService>().As<IUserService>().InstancePerLifetimeScope(); // Set the dependency resolver for Web API.
var webApiResolver = new AutofacWebApiDependencyResolver(container);
apiResolver = webApiResolver;
GlobalConfiguration.Configuration.DependencyResolver = webApiResolver; // Set the dependency resolver for MVC.
var resolver = new AutofacDependencyResolver(container);
mvcResolver = resolver;
DependencyResolver.SetResolver(mvcResolver);
}
} public interface IUserService
{
} public class UserService : IUserService
{
}
我们分别定义了两个静态变量mvcResolver和apiResolver来存储两个不同的容器,并注册了一组服务,指定其生命周期为InstancePerLifetimeScope,先看看Mvc的容器
public class HomeController : Controller
{
IUserService _userservice; public HomeController(IUserService userService)
{
_userservice = userService;
var a = DependencyResolver.Current.GetService<IUserService>();
var b = WebApiApplication.mvcResolver.GetService<IUserService>();
var c1 = ReferenceEquals(userService, a); //true
var c2 = ReferenceEquals(userService, b); //true
var c3 = ReferenceEquals(b, a); //true
}
} public class ValuesController : ApiController
{
IUserService _userservice; public ValuesController(IUserService userService)
{
_userservice = userService;
var a = GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(IUserService));
var b = WebApiApplication.apiResolver.GetService(typeof(IUserService));
var c1 = ReferenceEquals(userService, a); //false
var c2 = ReferenceEquals(userService, b); //false
var c3 = ReferenceEquals(b, a); //true
}
}
发现通过GlobalConfiguration.Configuration.DependencyResolver来获取的对象,竟然不等于构造函数解析出来的对象,有点毁三观。说明它并不是当前上下文的对象,也就是说这个对象的生命周期不在控制范围内。
那么Mvc和WebApi可不可以用同一个容器来指定呢?
我们先来看看stackoverflow上的这篇文章:Is it possible to configure Autofac to work with ASP.NET MVC and ASP.NET Web Api
其实Mvc和WebApi分别是两个独立的依赖解析器,这点没什么问题,一个是System.Web.Mvc.IDependencyResolver另一个是System.Web.Http.Dependencies.IDependencyResolver,两个互相不串。
最后,一个很重要的对象来了,那就是Autofac.IComponentContext,它就是解析的上下文,通过它来解析的对象是符合当前上下文的,我们再来看看之前的例子:
public class HomeController : Controller
{
IUserService _userservice; public HomeController(IUserService userService, IComponentContext com)
{
_userservice = userService;
var a = DependencyResolver.Current.GetService<IUserService>();
var b = WebApiApplication.mvcResolver.GetService<IUserService>();
var d = com.Resolve<IUserService>();
var d1 = ReferenceEquals(userService, d); //true
var c1 = ReferenceEquals(userService, a); //true
var c2 = ReferenceEquals(userService, b); //true
var c3 = ReferenceEquals(b, a); //true
}
}
//WebApi:
public class ValuesController : ApiController
{
IUserService _userservice; public ValuesController(IUserService userService, IComponentContext com)
{
_userservice = userService;
var a = GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(IUserService));
var b = WebApiApplication.apiResolver.GetService(typeof(IUserService));
var d = com.Resolve<IUserService>();
var d1 = ReferenceEquals(userService, d); //true
var c1 = ReferenceEquals(userService, a); //false
var c2 = ReferenceEquals(userService, b); //false
var c3 = ReferenceEquals(b, a); //true
}
}
参考:
ASP .Net 4 Web Api RC + Autofac manual resolving
希望对你有帮助,如有错误,欢迎指出! 用属性自动注入需要是public,
如果,能支持 protected 注入,那就完美了
转:autofac在mvc和webapi集成的做法的更多相关文章
- autofac解析Mvc和Webapi的坑
我们在项目中很早就开始使用autofac,也以为知道与mvc和webapi集成的做法. var builder = new ContainerBuilder(); // Mvc Register bu ...
- autofac + owin + webform + mvc + webapi集成demo
http://git.oschina.net/shiningrise/AutofacOwinDemo using Microsoft.Owin; using Owin; using System.We ...
- Autofac 同时支持MVC 与Webapi
1.引用 using Autofac; using Autofac.Integration.Mvc; using Autofac.Integration.WebApi; 2.在Global中的Appl ...
- AutoFac mvc和WebAPI 注册Service (接口和实现)
AutoFac mvc和WebAPI 注册Service (接口和实现) 1.准备组件版本:Autofac 3.5.0 Autofac.Integration.Mvc 3.3.0.0 (I ...
- 【半小时大话.net依赖注入】(下)详解AutoFac+实战Mvc、Api以及.NET Core的依赖注入
系列目录 上|理论基础+实战控制台程序实现AutoFac注入 下|详解AutoFac+实战Mvc.Api以及.NET Core的依赖注入 前言 本来计划是五篇文章的,每章发个半小时随便翻翻就能懂,但是 ...
- AutoFac在MVC中的使用
在asp.net mvc控制器中使用Autofac来解析依赖 如下Controller中使用构造函数依赖注入接口IUserService: public IUserService _IUserServ ...
- 记一次autofac+dapper+mvc的框架搭建实践
1,环境 .net framework4.7.2,Autofac,Autofac.Mvc5,sql server 2,动机 公司项目用的是ef,之前留下代码的大哥,到处using,代码没有分层,连复用 ...
- 给Asp.Net MVC及WebApi添加路由优先级
一.为什么需要路由优先级 大家都知道我们在Asp.Net MVC项目或WebApi项目中注册路由是没有优先级的,当项目比较大.或有多个区域.或多个Web项目.或采用插件式框架开发时,我们的路由注册很可 ...
- Autofac.Integration.Mvc分析
Autofac.Integration.Mvc static ILifetimeScope LifetimeScope { get { return (ILifetimeScope)HttpConte ...
随机推荐
- Delphi中的dll操作
利用delphi dll wizard进行dll的编写. 创建:保存时改dll名称 library test2; uses SysUtils, Classes, forms, dialogs; {$R ...
- Windows常见窗口样式和控件风格
Windows常见窗口样式和控件风格 王佰营 徐丽红 一.窗口样式 WS_POPUP 弹出式窗口(不能与WS_CHILDWINDOW样式同时使用)WS_CHILDWINDOW 子窗口(不能与WS_PO ...
- js在页面输出信息的几种方式alert,confirm,prompt,document.write
- Vue.js之组件嵌套
Vue.js中组件嵌套有两种方式 第一种:注册全局组件 例如在components文件夹下新建一个User.vue组件,然后在main.js文件中注册全局组件 //注册全局组件 Vue.compone ...
- ubuntu安装deb文件
install the deb-package, e.g. using the Terminal command$ sudo apt install <path-to-smartgit-deb- ...
- sql server扫盲系列
本系列为入门级,不会介绍过于深入的知识.为防止不道德转载(特别是红黑联盟,把我原文地址删掉,其他照搬,无节操无道德),尽可能打上水印和加上原文地址,读者看的不爽请见谅.原文地址:http://blog ...
- Django进阶项目
本来想上午轻轻松松搞定,没想到还是出了其他的问题,好在最后都解决了 在middleware.py当中 # -*- coding:utf-8 -*- __author__ = 'feimao' impo ...
- LeetCode:路径总和【112】
LeetCode:路径总和[112] 题目描述 给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和. 说明: 叶子节点是指没有子节点的节点. 示例 ...
- ThinkPHP框架基础知识一
ThinkPHP是一个快速.兼容而且简单的轻量级国产PHP开发框架,诞生于2006年初,原名FCS,2007年元旦正式更名为ThinkPHP,遵循Apache2开源协议发布,从Struts结构移植过来 ...
- 每天一个Linux命令(55)systemctl命令
systemctl命令是系统服务管理器指令,它实际上将 service 和 chkconfig 这两个命令组合到一起. (1)用法: 用法: systemctl [参数] [服务 ...