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
    {
        /// <summary>
        /// 负责调用autofac框架实现业务逻辑层和数据仓储层程序集中的类型对象的创建
        /// 负责创建MVC控制器类的对象(调用控制器中的有参构造函数),接管DefaultControllerFactory的工作
        /// </summary>
        public static void Register()
        {
            //实例化一个autofac的创建容器
            var builder = new ContainerBuilder();
            //告诉Autofac框架,将来要创建的控制器类存放在哪个程序集 (UI),从当前运行的bin目录下加载程序集
            Assembly controllerAss = Assembly.Load("cms.Web");
            builder.RegisterControllers(controllerAss);

            //告诉autofac框架注册数据仓储层所在程序集中的所有类的对象实例
            Assembly respAss = Assembly.Load("cms.DAL");
            //以接口形式保存被创建类的对象实例
            builder.RegisterTypes(respAss.GetTypes()).AsImplementedInterfaces();

            //告诉autofac框架注册业务逻辑层所在程序集中的所有类的对象实例
            Assembly serpAss = Assembly.Load("cms.BLL");
            //以接口形式保存被创建类的对象实例
            builder.RegisterTypes(serpAss.GetTypes()).AsImplementedInterfaces();

            //创建一个Autofac的容器
            var container = builder.Build();
            //移除原本的mvc的容器,使用AutoFac的容器,将MVC的控制器对象实例交由autofac来创建
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
    }
}

注意:UI层需要引用dal和bll层

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

        public InewsBLL bll { get; set; }
        public NewsController(InewsBLL _ibll)
        {
            bll = _ibll;
        }
        [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

转载于:https://www.cnblogs.com/webapi/p/10563735.html

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值