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

  1. 注册当前程序集下的所有Controller

    1. builder.RegisterControllers(typeof(MvcApplication).Assembly);
  2. 注册单个Controller
    1. builder.RegisterType<HomeController>().InstancePerRequest();

  注册ModelBinder

  1. 在启动项中注册ModelBinder
    1. builder.RegisterModelBinders(typeof(MvcApplication).Assembly);
      builder.RegisterModelBinderProvider();
  2. 自定义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

  1. 启动项设置

    // OPTIONAL: Register web abstractions like HttpContextBase.
      builder.RegisterModule<AutofacWebTypesModule>();

  2. 实例(在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层实现属性注入

  1. 启动项设置
    builder.RegisterSource(new ViewRegistrationSource());
  2. 实现自定义的ViewPage

    这里的例子使用的是一个强类型的View,所以实现了一个泛型ViewPage

     public abstract class CustomViewPage<T> : WebViewPage<T>
        {
            public ILogger Logger { get; set; }
        } 
  3. 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启用属性设置

  1. 启动项设置

    // OPTIONAL: Enable property injection into action filters.
    builder.RegisterFilterProvider();

  2. 自定义Filter
 public class CustomActionFilter : ActionFilterAttribute
    {
        public ILogger Logger { get; set; }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            Logger.Log("OnActionExecuting");
        }
    }

 

posted @ 2016-12-10 15:43  麻将我会  阅读(1902)  评论(3编辑  收藏  举报