1,環境 .net framework4.7.2,Autofac,Autofac.Mvc5,sql server 2,動機 公司項目用的是ef,之前留下代碼的大哥,到處using,代碼沒有分層,連復用都麽的,真的是夠了。現在要重構原來的系統,本著高效、簡潔、高耦合性的原則採用autofac + da ...
1,環境
.net framework4.7.2,Autofac,Autofac.Mvc5,sql server
2,動機
公司項目用的是ef,之前留下代碼的大哥,到處using,代碼沒有分層,連復用都麽的,真的是夠了。現在要重構原來的系統,本著高效、簡潔、高耦合性的原則採用autofac + dapper的設計(其實我更像用core來做,core速度更快,配置更簡單,而且我不想一直用老技術,但是公司大哥不讓啊。。。)
3,代碼
先引用如下幾個包 autofac、autofac.mvc5、autofac.WebApi2
項目結構是這樣,比較簡單
autofac 配置代碼
using Autofac; using Autofac.Integration.Mvc; using Autofac.Integration.WebApi; using AutoFac.Dapper.DataBase; using System.Linq; using System.Reflection; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace AutoFac.Dapper.Test { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); WebApiConfig.Register(GlobalConfiguration.Configuration); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); var builder = new ContainerBuilder(); //註冊controller builder.RegisterControllers(Assembly.GetExecutingAssembly()); builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); //載入要註入的程式集 var iServices = Assembly.Load("AutoFac.Dapper.IService"); var services = Assembly.Load("AutoFac.Dapper.Service"); //根據名稱約定(服務層的介面和實現均以Service結尾),實現服務介面和服務實現的依賴 builder.RegisterAssemblyTypes(iServices, services) .Where(t => t.Name.EndsWith("Service")) .AsImplementedInterfaces().InstancePerRequest(); //註冊主從庫的連接對象,每次請求只有一個庫的hashcode都是一個 這裡分了倆個是為了讀寫分離設計的 builder.RegisterType<DbMasterSession>().InstancePerRequest(); builder.RegisterType<DbSlaverSession>().InstancePerRequest(); //創建一個Autofac的容器 var container = builder.Build(); //將MVC的控制器對象實例 交由autofac來創建 DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container); } } }
dapper對象的代碼
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AutoFac.Dapper.DataBase { /// <summary> /// 公共的資料庫連接管理類,用於使用Autofac時可以自動關閉DbConnection /// </summary> public sealed class DbMasterSession : IDisposable { bool _disposed; /// <summary> /// 用於管理資料庫連接 /// </summary> public IDbConnection DbConnection { get; set; } public DbMasterSession() { DbConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["MasterConStr"].ConnectionString); } /// <summary> /// 關閉DbConnection /// </summary> public void Dispose() { if (this._disposed) return; this._disposed = true; if (this.DbConnection == null) return; if (this.DbConnection.State != ConnectionState.Closed) this.DbConnection.Close(); } } }
項目地址: https://gitee.com/siming.liu/AutoFac.Dapper.Web