1. 程式人生 > >.NETCore Sqlserver下對Dapper的擴展支持

.NETCore Sqlserver下對Dapper的擴展支持

tom mage finally ons ont open() ice security tran

這裏我們自定義一個IServiceCollection的擴展,例如下面我的擴展

services.AddDapperContext(dapperoptions =>
            {
                dapperoptions.ConnectionString = "Data Source=192.168.0.42;Initial Catalog=NET.Core;User ID=sa;password=lym123!@#;Integrated Security=false";
            });

添加了對數據庫連接字符串設置,當然你也可以設置更多的參數,委托等等,這裏簡單演示下自定義dapper下的數據庫訪問,下面是擴展設置

 1  public static class DapperMiddlewareExtension
 2     {
 3 
 4         public static IServiceCollection AddDapperContext<TDapperContext>(this IServiceCollection serviceCollection, Action<DapperOptions> optionsAction = null, ServiceLifetime contextLifetime = ServiceLifetime.Scoped, ServiceLifetime optionsLifetime = ServiceLifetime.Scoped) where
TDapperContext : DapperContext 5 { 6 serviceCollection.Configure(optionsAction); 7 serviceCollection.AddTransient<IDataProvider, SqlServerDataProvider>(); 8 serviceCollection.AddSingleton<TDapperContext>(); 9 return serviceCollection;
10 } 11 /// <summary> 12 /// 添加服務 13 /// </summary> 14 /// <param name="serviceCollection"></param> 15 /// <param name="optionsAction"></param> 16 /// <param name="contextLifetime"></param> 17 /// <param name="optionsLifetime"></param> 18 /// <returns></returns> 19 public static IServiceCollection AddDapperContext(this IServiceCollection serviceCollection, Action<DapperOptions> optionsAction = null, ServiceLifetime contextLifetime = ServiceLifetime.Scoped, ServiceLifetime optionsLifetime = ServiceLifetime.Scoped) 20 { 21 serviceCollection.Configure(optionsAction); 22 serviceCollection.AddTransient<IDataProvider, SqlServerDataProvider>(); 23 serviceCollection.AddSingleton<DapperContext>(); 24 return serviceCollection; 25 }

這裏DI相關的數據庫訪問類,這裏最終要的一點就是我們在startup中設置的連接的字符串,在數據庫DI類中怎麽得到來訪問數據庫呢?

serviceCollection.Configure(optionsAction); 將委托Action配置到IOptions接口中
下面來看下我們的DapperContext
 public class DapperContext 
    {
        DapperOptions _dapperOptions;
        IDataProvider _dataProvider;
        public DapperContext(IOptions<DapperOptions> options, IDataProvider dataProvider)
        {
            _dapperOptions = options.Value;
            _dataProvider = dataProvider;
        }

      


        #region 創建Dapper相關連接


        private IDbConnection CreateConnection(bool ensureClose = true)
        {

            var conn = _dataProvider.CreateConnection();
            conn.ConnectionString = _dapperOptions.ConnectionString;
            conn.Open();

            return conn;
        }
        private IDbConnection _connection;
        private IDbConnection Connection
        {
            get
            {
                if (_connection == null || _connection.State != ConnectionState.Open)
                {
                    _connection = CreateConnection();
                }

                return _connection;
            }
        }

        public void insertTest(string sql)
        {


            var conn = Connection;
            try
            {
                conn.Execute(sql);
            }

            finally
            {
                if (_connection != null)
                {
                    _connection.Close();
                    _connection = null;
                }
            }


        }

在寫好相關的數據庫訪問連接類處理
建立自己的業務服務,這裏寫的比較簡單
 public interface ICustomDapperContext 
    {

        void Insert(string sql);
       
    }

 public class CustomDapperContext : ICustomDapperContext
    {
        DapperContext _dapperContext;
        public CustomDapperContext(DapperContext dapperContext)
        {
            _dapperContext = dapperContext;
        }
        public void Insert(string sql)
        {
            _dapperContext.insertTest(sql);
        }
    }

然後在Controller層DI下
ICustomDapperContext _context;
        public HomeController(ICustomDapperContext context)
        {
            _context = context;
        }
        public IActionResult Index()
        {
          _context.Insert("insert into Tb_UserLogin(UserName,UserPwd,[Order],IsDelete) values (‘UserName‘,‘UserName‘,0,0)");
            return View();
        }

執行後數據庫添加成功

技術分享圖片

下面是我自定義的中間件的相關類

技術分享圖片


.NETCore Sqlserver下對Dapper的擴展支持