如何使用 .net core 中的依赖注入处理与 dapper 的 postgresql db 连接?

Sun*_*y12 5 npgsql dapper asp.net-core asp.net-core-3.0

我在我的 asp.net 核心 Web API 项目中使用 Dapper ORM 进行数据库操作。现在我每次都打开新的数据库连接并在using块中使用它,以便在范围结束时将它们处理掉。但是我希望在不使用using块的情况下处理所有这些连接,并且还想自动处理它们。我正在寻找一种方法来使用依赖注入来实现这一点,因为它们会自动处理实现 IDisposable 的对象。

这是我处理所有数据库连接的方式:

在我的基础存储库中创建了一个 GetConnection 属性:

private IDbConnection _connection;

public IDbConnection GetConnection
{
    get
    {
        _connection = new NpgsqlConnection("Connection String");
        return _connection;
    }
}
Run Code Online (Sandbox Code Playgroud)

使用块访问内部的属性:

public async Task<IEnumerable<T>> GetAllAsync()
{
    IEnumerable<T> records = null;

    using (IDbConnection connection = GetConnection)
    {
        //db operations
    }

    return records;
}
Run Code Online (Sandbox Code Playgroud)

那么如何使用依赖注入实现相同的功能,在需要时初始化 IDbconnection 并在请求结束时处理,而无需将 IDbconnection 封装在 using 块中?

简而言之,我想避免每次都使用 GetConnection 属性来创建数据库对象,并避免使用块来处理相同的对象。

Sun*_*y12 9

我是这样做的:

在startup.cs文件中添加瞬态服务

services.AddTransient<IDbConnection>((sp) => new NpgsqlConnection("connectionString"));
Run Code Online (Sandbox Code Playgroud)

在基础存储库构造函数中初始化 IDbconnection 对象,如下所示:

class  RepositoryBase
{
    protected IDbConnection _connection;

    protected RepositoryBase(IDbConnection dbConnection)
    {
         _connection = dbConnection;
    }
}
Run Code Online (Sandbox Code Playgroud)

并在我的存储库中执行数据库操作,例如

class XyzRepository : RepositoryBase
{
    public async Task<IEnumerable<T>> GetAllAsync()
    {
        IEnumerable<T> records = null;

        await _connection.ExecuteScalarAsync<object>("sqlQuery");

        return records;
    }

}
Run Code Online (Sandbox Code Playgroud)

这将在请求结束时自动处理 IDbconnection 对象,而不使用using块。

参考答案:How do I handle Database Connections with Dapper in .NET?