开发环境: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 > )
{
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

最新文章

  1. C++ create_task详解
  2. iOS工程集成支付宝错误Undefined symbols for architecture armv7
  3. react native下android开发环境搭建
  4. node.js之看懂package.json依赖库版本控制
  5. reactjs入门到实战(三)---- 组件详解
  6. apt-get下载的文件
  7. SQL &amp; PL/SQL 模块总结
  8. Android 网络编程 Socket
  9. AutoLayout框架Masonry使用心得
  10. 想做一个整合开源安全代码扫描工具的代码安全分析平台 - Android方向调研
  11. informix 查看数据库空间名
  12. 蓝桥杯-凑算式-java
  13. css写出三角形(兼容IE)
  14. log4j java项目中的配置
  15. CentOS7中KVM虚拟机内存、CPU调整
  16. 实现文件上传 你get了吗???
  17. dede后台目录暴力猜解仅限于windows
  18. Linux分区设置
  19. [ERR] Node is not empty. Either the node already knows other nodes (check with C
  20. Transparency Sort Mode

热门文章

  1. Python itertools模块详解
  2. mysql查询根据时间排序
  3. 在UnrealEngine中用Custom节点实现高斯模糊
  4. BZOJ.4897.[Thu Summer Camp2016]成绩单(区间DP)
  5. BZOJ4167 : 永远的竹笋采摘
  6. python网络编程(十二)
  7. C# Socket网络编程精华篇 (转)
  8. Python内置GUI模块Tkinter的几点笔记
  9. SuperWebSocket与Cocos2dx通信时执行不了命令的问题
  10. AnjularJS表单回车提交事件