.NETCore Sqlserver下對Dapper的擴充支援

來源:互聯網
上載者:User

標籤:示範   time   figure   life   interface   業務   conf   tap   ansi   

這裡我們自訂一個IServiceCollection的擴充,例如下面我的擴充

services.AddDapperContext(dapperoptions =>            {                dapperoptions.ConnectionString = "Data Source=192.168.0.42;Initial Catalog=NET.Core;User ID=sa;[email protected]#;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的擴充支援

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.