zoukankan      html  css  js  c++  java
  • Asp.Net MVC三层架构之autofac使用教程

    开发环境:vs2015、.net4.5.2、mvc5、ef6

    Autofac简介

    IOC控制反转(Inversion of Control,缩写为IOC),Autofac是一个开源的依赖注入框架,Autofac是asp.net中比较常用的IOC容器之一

    IOC的目标是消除代码中的new(实例化)语句,把实例化类的控制权转移到别的地方,这个地方通常会在一个程序加载时只执行一次的全局方法中,达到解耦的目的。

    DI依赖注入(Dependency Injection,缩写为DI),组件之间依赖关系由容器在运行期决定,形象的说,即由容器动态的将某个依赖关系注入到组件之中。依赖注入的目的并非为软件系统带来更多功能,而是为了提升组件重用的频率,并为系统搭建一个灵活、可扩展的平台。通过依赖注入机制,我们只需要通过简单的配置,而无需任何代码就可指定目标需要的资源,完成自身的业务逻辑,而不需要关心具体的资源来自何处,由谁实现。

    三层架构

    Autofac安装

    通过Nuget安装Autofac和Autofac.Mvc5

    Autofac配置

    1、App_Start文件夹里新建AutoFacConfig.cs

    using System;
    using System.Reflection;
    using System.Web.Mvc;
    using Autofac;
    using Autofac.Integration.Mvc;
    namespace cms.Web
    {
        public class AutoFacConfig
        {
            public static void Register()
            {
                var builder = new ContainerBuilder();
    
                builder.RegisterControllers(Assembly.GetCallingAssembly())//注册mvc的Controller
                    .PropertiesAutowired();//属性注入
    
    
                //1、无接口类注入
                //builder.RegisterType<BLL.newsClassBLL>().AsSelf().InstancePerRequest().PropertiesAutowired();
                
    
                //2、有接口类注入
                //注入BLL,UI中使用
                builder.RegisterAssemblyTypes(typeof(BLL.BaseBLL<>).Assembly)
                    .AsImplementedInterfaces()  //是以接口方式进行注入
                    .InstancePerRequest()       //每次http请求
                    .PropertiesAutowired();     //属性注入
    
                //注入DAL,BLL层中使用
                builder.RegisterAssemblyTypes(typeof(DAL.BaseDAL<>).Assembly).AsImplementedInterfaces()
                    .InstancePerRequest().PropertiesAutowired();     //属性注入
    
                //Cache的注入,使用单例模式
                //builder.RegisterType<RedisCacheManager>()
                //    .As<ICacheManager>()
                //    .SingleInstance()
                //    .PropertiesAutowired();
    
                //移除原本的mvc的容器,使用AutoFac的容器,将MVC的控制器对象实例交由autofac来创建
                var container = builder.Build();
                DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
    
            }
        }
    }

    2、Global.asax配置Autofac

    protected void Application_Start()
            {
                AreaRegistration.RegisterAllAreas();
    
                WebApiConfig.Register(GlobalConfiguration.Configuration);
                FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
                RouteConfig.RegisterRoutes(RouteTable.Routes);
                BundleConfig.RegisterBundles(BundleTable.Bundles); 
    
                BundleTable.EnableOptimizations = true;//js、css压缩
                MiniProfilerEF6.Initialize();//MiniProfiler监控ef
                GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();//webapi默认JSON
                AutoFacConfig.Register();//autofac:控制反转,依赖注入配置
            }

    Autofac使用

    使用构造函数注入

    using System;
    using System.Web.Mvc;
    using cms.Model;
    using cms.IBLL;
    //using cms.BLL;   
    
    //不需要应用bll,但需要引用IBLL
    namespace cms.Web.Areas.Admin.Controllers
    {
        public class NewsController : BaseController
        {
            //未使用Autofac前直接实例化的写法
            //public newsBLL bll = new newsBLL();
    
          //autofac属性注入 public InewsClassBLL bll { get; set; }

    [HttpPost] [ValidateAntiForgeryToken] [ValidateInput(false)] public ActionResult Add(news vmodel,FormCollection forms) { news model = new news(); model.title = Request["title"]; model.times = DateTime.Now; model = bll.Add(model); if (model.ID > 0) { return RedirectToAction("list"); } ViewData["mess"] = "添加失败"; return View(vmodel); } public ActionResult Edit(int id) { news model = bll.Find(id); return View(model); } // GET: Admin/Admins/Delete/5 public ActionResult Delete(int id) { if (bll.Delete(id)) { return Redirect(Request.UrlReferrer.ToString()); } else { Common.JSHelper.AlertRedirect("操作失败", Request.UrlReferrer.ToString()); } return RedirectToAction("list"); } } }

     //ui层不再依赖于BLL,只依赖于IBLL,BLL可以随意变动

    end

  • 相关阅读:
    erlang开发环境(IDE)搭建
    Mono for android,Xamarin点击事件的多种写法
    .NET C#中处理Url中文编码问题
    第一天正式学习,定一个学习目标吧。
    想转行做开发了!
    Java JMS 程序基础 与 ActiveMQ 安装(一)
    JDBC 基础
    Linux 6.4 设置yum 为centOS源
    C++ 简单实现 依赖注入(IOC)
    安卓项目
  • 原文地址:https://www.cnblogs.com/webapi/p/10563735.html
Copyright © 2011-2022 走看看