ASP.NET MVC 5 使用autofac實現DI

來源:互聯網
上載者:User

標籤:book   ice   property   abs   wpa   ide   nbsp   erb   alt   

  • 使用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");        }    }

 

ASP.NET MVC 5 使用autofac實現DI

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.