How do I handle Database Connections with Dapper in .NET?

前端 未结 9 2050
闹比i
闹比i 2020-12-07 07:52

I\'ve been playing with Dapper, but I\'m not sure of the best way to handle the database connection.

Most examples show the connection object being created in the

9条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-07 08:36

    I do it like this:

    internal class Repository : IRepository {
    
        private readonly Func _connectionFactory;
    
        public Repository(Func connectionFactory) 
        {
            _connectionFactory = connectionFactory;
        }
    
        public IWidget Get(string key) {
            using(var conn = _connectionFactory()) 
            {
                return conn.Query(
                   "select * from widgets with(nolock) where widgetkey=@WidgetKey", new { WidgetKey=key });
            }
        }
    }
    

    Then, wherever I wire-up my dependencies (ex: Global.asax.cs or Startup.cs), I do something like:

    var connectionFactory = new Func(() => {
        var conn = new SqlConnection(
            ConfigurationManager.ConnectionStrings["connectionString-name"];
        conn.Open();
        return conn;
    });
    

提交回复
热议问题