记一次autofac+dapper+mvc的框架搭建实践

1,环境

.net framework4.7.2,Autofac,Autofac.Mvc5,sql server

2,动机

公司项目用的是ef,之前留下代码的大哥,到处using,代码没有分层,连复用都么的,真的是够了。现在要重构原来的系统,本着高效、简洁、高耦合性的原则采用autofac + dapper的设计(其实我更像用core来做,core速度更快,配置更简单,而且我不想一直用老技术,但是公司大哥不让啊。。。)

3,代码

先引用如下几个包 autofac、autofac.mvc5、autofac.WebApi2

记一次autofac+dapper+mvc的框架搭建实践

项目结构是这样,比较简单

记一次autofac+dapper+mvc的框架搭建实践

 

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

上一篇:.net core 注入机制与Autofac


下一篇:Ioc容器Autofac系列(1)-- 初窥