ASP.NET MVC 5 使用autofac实现DI
https://www.cnblogs.com/LittleFeiHu/p/6155883.html
- 使用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 |
|
注册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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
|
注册相关的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 |
|
在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 |
|
为ActionFilter启用属性设置
- 启动项设置
// OPTIONAL: Enable property injection into action filters.
builder.RegisterFilterProvider(); - 自定义Filter
1 2 3 4 5 6 7 8 9 |
|