ASP.NET MVC 5 使用autofac实现DI
- 使用Nuget添加Autofac.MVC的引用
- 启动项设置
- 注册Controller
- 注册ModelBinder
- 注册相关的web abstraction
- 为View层启用属性注入
- 为Action Filter启用属性注入
使用Nuget添加Autofac.MVC的引用
启动项设置
protected void Application_Start(){AreaRegistration.RegisterAllAreas();RouteConfig.RegisterRoutes(RouteTable.Routes);var builder = new ContainerBuilder();builder.RegisterType<BookService>().As<IBookService>();builder.RegisterType<Logger>().As<ILogger>();// Register your MVC controllers. (MvcApplication is the name of// the class in Global.asax.)builder.RegisterControllers(typeof(MvcApplication).Assembly);// OPTIONAL: Register model binders that require DI.builder.RegisterModelBinders(typeof(MvcApplication).Assembly);builder.RegisterModelBinderProvider();// OPTIONAL: Register web abstractions like HttpContextBase.builder.RegisterModule<AutofacWebTypesModule>();// OPTIONAL: Enable property injection in view pages.builder.RegisterSource(new ViewRegistrationSource());// OPTIONAL: Enable property injection into action filters.builder.RegisterFilterProvider();// Set the dependency resolver to be Autofac.var container = builder.Build();DependencyResolver.SetResolver(new AutofacDependencyResolver(container));}
注册Controller
注册当前程序集下的所有Controller
- builder.RegisterControllers(typeof(MvcApplication).Assembly);
注册单个Controller
builder.RegisterType<HomeController>().InstancePerRequest();
注册ModelBinder
在启动项中注册ModelBinder
- builder.RegisterModelBinders(typeof(MvcApplication).Assembly);
builder.RegisterModelBinderProvider();
- builder.RegisterModelBinders(typeof(MvcApplication).Assembly);
自定义ModelBinder并且设置ModelBinderTypeAttribute
[ModelBinderType(typeof(Book))]public class BookModelBinder : IModelBinder{public ILogger logger;public BookModelBinder(ILogger logger){this.logger = logger;}public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext){HttpRequestBase request = controllerContext.HttpContext.Request;string title = request.Form.Get("Title");string BookID = request.Form.Get("BookID");string day = request.Form.Get("Day");string month = request.Form.Get("Month");string year = request.Form.Get("Year");return new Book { BookID=BookID, Title=title+":DI Test"+this.logger.Log("dsa")+request.Form.Get("HttpRequestBaseDI"), Date=year+"-"+month+"-"+day };}}
注册相关的Web Abstract Class
- 启动项设置
// OPTIONAL: Register web abstractions like HttpContextBase.
builder.RegisterModule<AutofacWebTypesModule>(); - 实例(在ModelBinder中使用HttpRequestBase)
[ModelBinderType(typeof(Book))]public class BookModelBinder : IModelBinder{ILogger logger;HttpRequestBase request1;public BookModelBinder(ILogger logger, HttpRequestBase request){this.logger = logger;this.request1 = request;}public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext){HttpRequestBase request = controllerContext.HttpContext.Request;request = request1;string title = request.Form.Get("Title");string BookID = request.Form.Get("BookID");string day = request.Form.Get("Day");string month = request.Form.Get("Month");string year = request.Form.Get("Year");return new Book { BookID=BookID, Title=title+":DI Test"+this.logger.Log("dsa")+request.Form.Get("HttpRequestBaseDI"), Date=year+"-"+month+"-"+day };}}
在View层实现属性注入
- 启动项设置
builder.RegisterSource(new ViewRegistrationSource());
- 实现自定义的ViewPage
这里的例子使用的是一个强类型的View,所以实现了一个泛型ViewPage
public abstract class CustomViewPage<T> : WebViewPage<T>
{
public ILogger Logger { get; set; }
} - View设置
@inherits MVC5Practices.Infrastructure.CustomViewPage<MVC5Practices.Infrastructure.Book>@{Layout = null;
}<!DOCTYPE html><html>
<head><meta name="viewport" content="width=device-width" /><title>ShowBook</title>
</head>
<body><div><h4>Book</h4><h5>@Logger.Log("dsa")</h5><hr /><dl class="dl-horizontal"><dt>@Html.DisplayNameFor(model => model.Title)</dt><dd>@Html.DisplayFor(model => model.Title)</dd><dt>@Html.DisplayNameFor(model => model.Date)</dt><dd>@Html.DisplayFor(model => model.Date)</dd></dl></div><p>@Html.ActionLink("Edit", "Edit", new { id = Model.BookID }) |@Html.ActionLink("Back to List", "Index")</p>
</body>
</html>
为ActionFilter启用属性设置
- 启动项设置
// OPTIONAL: Enable property injection into action filters.
builder.RegisterFilterProvider(); - 自定义Filter
public class CustomActionFilter : ActionFilterAttribute{public ILogger Logger { get; set; }public override void OnActionExecuting(ActionExecutingContext filterContext){Logger.Log("OnActionExecuting");}}
转载于:https://www.cnblogs.com/LittleFeiHu/p/6155883.html
ASP.NET MVC 5 使用autofac实现DI相关推荐
- ASP.NET MVC IOC 之AutoFac攻略
转于:http://www.cnblogs.com/WeiGe/p/3871451.html 一.为什么使用AutoFac? 之前介绍了Unity和Ninject两个IOC容器,但是发现园子里用Aut ...
- ASP.NET MVC中使用Autofac实现简单依赖注入
本文参考资料: 1.https://www.cnblogs.com/RayWang/p/11128554.html. 2.https://www.cnblogs.com/eedc/p/6127181. ...
- asp.net mvc Autofac 依赖注入框架 使用
Autofac是一款IOC框架,比较于其他的IOC框架,如Spring.NET,Unity,Castle等等所包含的,它很轻量级性能上非常高. 官方网站http://autofac.org/ 源码下载 ...
- [ASP.NET MVC 小牛之路]04 - 依赖注入(DI)和Ninject
特别提醒:本文编写时间是 2013 年,请根据目前 .NET 发展接收你所需的知识点. 为什么需要依赖注入 在[ASP.NET MVC 小牛之路]系列的理解MVC模式文章中,我们提到MVC的一个重要特 ...
- AutoFac IoC DI 依赖注入
AutoFac IoC DI 依赖注入 记录点点滴滴知识,为了更好的服务后来者! 一.为什么使用AutoFac? 之前介绍了Unity和Ninject两个IOC容器,但是发现园子里用AutoFac的貌 ...
- 我要学ASP.NET MVC 3.0(一): MVC 3.0 的新特性
摘要 MVC经过其1.0和2.0版本的发展,现在已经到了3.0的领军时代,随着技术的不断改进,MVC也越来越成熟.使开发也变得简洁人性化艺术化. 园子里有很多大鸟都对MVC了如指掌,面对问题犹同孙悟空 ...
- 模型(Model)– ASP.NET MVC 4 系列
为 MVC Music Store 建模 在 Models 目录中为专辑.艺术家.流派建模: public class Album { public virtual int AlbumId { get ...
- ASP.NET MVC入门到精通——Spring.net-业务层仓储
本系列目录:ASP.NET MVC4入门到精通系列目录汇总 上一节,我们已经把项目框架的雏形搭建好了,那么现在我来开始业务实现,在业务实现的过程当中,不断的来完善我们现有的框架. 1.假设我们来做一个 ...
- 不用asp.net MVC,用WebForm照样可以实现MVC(请看最后一句话)
在<避开WebForm天坑,拥抱ASP.Net MVC吧>这篇博客中我讲到了ASP.net WebForm由于一些先天的"诱导犯罪"的缺陷,现在用ASP.net MVC ...
最新文章
- Java虚拟机JVM学习06 自定义类加载器 父委托机制和命名空间的再讨论
- 从全球最大光伏展看中国光伏行业:火爆的背后是什么?
- MATLAB中多个一维数组的合并
- 燃烧学往年精选真题解析 2018-01-01
- 如何稀释 流事件 (如,onscroll、change、input、mouseover 等 事件)
- Python字符串模糊匹配库FuzzyWuzzy
- AndroidStudio_开发工具的设置_代码编辑器使用_新特性---Android原生开发工作笔记73
- Halcon——点胶机胶水路径应用(2)
- STC8H8K系列汇编和C51实战——实现跑马灯(汇编版)
- mysql 求几何平均值_回忆高中数学--各种平均数公式
- 小米盒子显示连不上服务器,小米盒子连不上WiFi?这七个技巧绝对管用
- 安卓-LBS地图显示
- 消息摘要(Message Digest)及其算法
- LeetCode——Symmetric Tree
- 如何防止短信验证被盗刷
- css3的含义是什么
- feign远程调用传参问题
- 一件衣服95元,如果消费满300元,可以打八五折。输入购买衣服数,输出需要支付的金额。
- 小飞学习Docker之使用容器
- 期货中的期什么意思(期货什么意思是什么)