https://www.cnblogs.com/LittleFeiHu/p/6155883.html
ASP.NET MVC 5 使用autofac实现DI
- 使用Nuget添加Autofac.MVC的引用
- 启动项设置
- 注册Controller
- 注册ModelBinder
- 注册相关的web abstraction
- 为View层启用属性注入
- 为Action Filter启用属性注入
使用Nuget添加Autofac.MVC的引用
启动项设置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | 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();
-
自定义ModelBinder并且设置ModelBinderTypeAttribute
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | [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)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | [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设置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | @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
1 2 3 4 5 6 7 8 9 | public class CustomActionFilter : ActionFilterAttribute { public ILogger Logger { get ; set ; } public override void OnActionExecuting(ActionExecutingContext filterContext) { Logger.Log( "OnActionExecuting" ); } } |