简体   繁体   中英

When using a repository pattern with Dapper, is it necessary to open and close db connections?

In an article about implementing a repository with Dapper ( Using Dapper.NET ORM... ), there is the following code:

public class UserRepository : IUserRepository
{
    private IDbConnection _db = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
    public List<User> GetAll()
    {
        return this._db.Query<User>("SELECT * FROM Users").ToList();
    }

    public User Find(int id)
    {
        return this._db.Query<User>("SELECT * FROM Users WHERE UserID = @UserID", new { id }).SingleOrDefault();
    }

    public User Add(User user)
    {
        var sqlQuery = "INSERT INTO Users (FirstName, LastName, Email) VALUES(@FirstName, @LastName, @Email); " + "SELECT CAST(SCOPE_IDENTITY() as int)";
        var userId = this._db.Query<int>(sqlQuery, user).Single();
        user.UserID = userId;
        return user;
    }
}

Regarding the private IDbConnection, why is this never opened or closed in the individual methods? I've seen this elsewhere as well. Is there some sugar around this pattern? My instinct is to wrap each return in a using followed by an _db.Open(); like below, but, again, I've seen this not being done in several other references on the web.

public List<User> GetAll()
{
    using (_db)   //or (IDbConnection _db = new SqlConnection(myConnectionString))
    {
        _db.Open();
        return this._db.Query<User>("SELECT * FROM Users").ToList();
    }
}

Dapper will indeed open and close automatically if it detects a closed connection. So if you don't want to have to do that bit: it should still work fine. The main downside about that would be that you can't easily spare a transaction over a closed connection, so if you intend to use connection-level transactions it may be better to start with connection lifetime management built in too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM