记一次autofac+dapper+mvc的框架搭建实践
程序员文章站
2022-06-28 20:39:30
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(); } } }
下一篇: 字体不能随便用,侵权竟被索赔上百万!