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>();html

  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,因此實現了一個泛型ViewPageweb

     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();ide

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

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            Logger.Log("OnActionExecuting");
        }
    }
相關文章
相關標籤/搜索