绝世好文 转:http://blog.csdn.net/fanbin168/article/details/51293218
1
IOC概念(很重要)

项目
先引入AutoFac 和AutoFac MVC两个程序集到项目中
然后我们在MVC(UI层)的App_Start文件夹下创建一个AutoFacConfig.cs类
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
-
- namespace FB.CMS.MvcSite.App_Start
- {
- using Autofac;
- using Autofac.Integration.Mvc;
- using System.Reflection;
- using System.Web.Mvc;
-
-
-
-
- public class AutoFacConfig
- {
-
-
- public static void Register()
- {
-
-
-
-
- ContainerBuilder builder = new Autofac.ContainerBuilder();
-
-
-
- Assembly controllerAss = Assembly.Load("FB.CMS.MvcSite");
-
-
- builder.RegisterControllers(controllerAss);
-
-
-
-
-
-
- Assembly repositoryAss = Assembly.Load("FB.CMS.Repository");
-
- Type[] rtypes = repositoryAss.GetTypes();
-
- builder.RegisterTypes(rtypes)
- .AsImplementedInterfaces();
-
-
- Assembly servicesAss = Assembly.Load("FB.CMS.Services");
-
- Type[] stypes = servicesAss.GetTypes();
-
- builder.RegisterTypes(stypes)
- .AsImplementedInterfaces();
-
-
-
- var container = builder.Build();
-
-
-
-
-
-
-
-
-
- DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
-
-
-
-
-
-
-
-
-
-
-
-
-
- }
- }
- }
然后我们在Global.asax文件中的Application_Start()方法中来调用这个类
- using FB.CMS.MvcSite.App_Start;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Http;
- using System.Web.Mvc;
- using System.Web.Optimization;
- using System.Web.Routing;
-
- namespace FB.CMS.MvcSite
- {
-
-
-
- public class MvcApplication : System.Web.HttpApplication
- {
- protected void Application_Start()
- {
-
- AreaRegistration.RegisterAllAreas();
-
- WebApiConfig.Register(GlobalConfiguration.Configuration);
- FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
- RouteConfig.RegisterRoutes(RouteTable.Routes);
- BundleConfig.RegisterBundles(BundleTable.Bundles);
-
-
-
-
-
- AutoFacConfig.Register();
- }
- }
- }
使用
Home控制器
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
-
- namespace FB.CMS.MvcSite.Controllers
- {
- using FB.CMS.IServices;
- public class HomeController : Controller
- {
- IsysFunctionServices dal;
- public HomeController(IsysFunctionServices dal)
- {
- this.dal = dal;
- }
-
- public ActionResult Index()
- {
- var a = dal.QueryWhere(r => r.fID > 20).ToList();
- return View();
- }
- }
- }
用AutoFac 在一个控制器下通过构造函数,注入多个对象的时候,我们可以对BaseDal进行优化
BaseDal类
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
-
- namespace FB.CMS.Repository
- {
- using FB.CMS.IRepository;
- using System.Data.Entity;
- using System.Data.Entity.Infrastructure;
- using System.Linq.Expressions;
- using System.Runtime.Remoting.Messaging;
- using System.Threading;
- public class BaseDal<TEntity> : IBaseDal<TEntity> where TEntity : class
- {
-
-
-
- public BaseDbContext db
- {
- get
- {
-
- string threadName = typeof(BaseDbContext).FullName;
-
- object dbObj = CallContext.GetData(threadName);
-
- if (dbObj == null)
- {
-
- dbObj = new BaseDbContext();
-
- CallContext.SetData(threadName, dbObj);
- return dbObj as BaseDbContext;
- }
- return dbObj as BaseDbContext;
- }
-
- }
- DbSet<TEntity> _dbset;
- public BaseDal()
- {
- this._dbset = db.Set<TEntity>();
- }
-
- #region 增加
- public void AddEnity(TEntity model)
- {
- if (model == null)
- {
- throw new Exception("moddel不能为null");
- }
- this._dbset.Add(model);
-
-
- }
-
- #endregion
-
- #region 物理删除
-
-
-
-
-
- public void DeleteEntity(TEntity model, bool isaddedContext)
- {
- if (model == null)
- {
- throw new Exception("DeleteEntity方法中的model不能为null");
- }
-
- if (isaddedContext == true)
- {
- this._dbset.Attach(model);
-
- }
- this._dbset.Remove(model);
- }
-
- #endregion
-
- #region 查寻
-
-
-
-
-
- public IQueryable<TEntity> QueryWhere(Expression<Func<TEntity, bool>> where)
- {
- return this._dbset.Where(where);
- }
-
-
-
-
-
-
-
- public IQueryable<TEntity> QueryJoin(Expression<Func<TEntity, bool>> where, string[] tablesName)
- {
- if (tablesName == null || tablesName.Any() == false)
- {
- throw new Exception("连表查询最少也要一个表,所有QueryJoin方法中tablesName中最少也需要有一个表名");
- }
-
- DbQuery<TEntity> query = this._dbset;
- foreach (string tableName in tablesName)
- {
-
- query = query.Include(tableName);
- }
- return query.Where(where);
- }
-
-
-
-
-
-
-
-
-
-
-
- public IQueryable<TEntity> QueryByPage<TKey>(int pageindex, int pagesize, out int rowCount, Expression<Func<TEntity, TKey>> order, Expression<Func<TEntity, bool>> where)
- {
-
- rowCount = this._dbset.Count(where);
-
-
- return this._dbset.Where(where).OrderByDescending(order).Skip((pageindex - 1) * pagesize).Take(pagesize);
-
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- public List<TElement> RunProc<TElement>(string sql, params object[] prms)
- {
- return db.Database.SqlQuery<TElement>(sql, prms).ToList();
- }
- #endregion
-
- #region 编辑
-
-
-
-
-
- public void EditEntity(TEntity model, string[] propertyNames)
- {
- if (model == null)
- {
- throw new Exception("EditEntity方法中的参数model不能为null");
- }
- if (propertyNames.Any() == false || propertyNames == null)
- {
- throw new Exception("EditEntity方法中的参数propertyNames最少需要一个属性");
- }
- System.Data.Entity.Infrastructure.DbEntityEntry entry = db.Entry(model);
- entry.State = System.Data.EntityState.Unchanged;
- foreach (string item in propertyNames)
- {
- entry.Property(item).IsModified = true;
- }
- db.Configuration.ValidateOnSaveEnabled = false;
- }
-
- #endregion
-
- #region 统一保存
- public int SaveChanges()
- {
- return db.SaveChanges();
- }
- #endregion
- }
- }
Home控制器
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
-
- namespace FB.CMS.Site.Controllers
- {
- using FB.CMS.IRepository;
-
- public class HomeController : Controller
- {
- IsysFunctionRepository fundal;
- IsysKeyValueRepository kvdal;
-
-
-
-
-
-
-
-
-
-
- public HomeController(IsysFunctionRepository fundal, IsysKeyValueRepository kvdal)
- {
- this.fundal = fundal;
- this.kvdal = kvdal;
- }
-
- public ActionResult Index()
- {
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- var model = fundal.QueryWhere(r => r.fID == 20).FirstOrDefault();
- model.fName = "默认888";
-
-
- var model2 = kvdal.QueryWhere(r => r.KID == 3).FirstOrDefault();
- model2.KName = "公司88";
-
- fundal.SaveChanges();
-
- return View(model);
-
- }
-
- }
- }
AutoFac (控制反转IOC 与依赖注入DI)
原文:http://www.cnblogs.com/moy-1313133/p/6839340.html