.NETCore Sqlserver下對Dapper的擴展支持


這里我們自定義一個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();
        }

執行后數據庫添加成功

 

 

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

 

 
        

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM