小编Sun*_*y12的帖子

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

我在我的 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 属性来创建数据库对象,并避免使用块来处理相同的对象。

npgsql dapper asp.net-core asp.net-core-3.0

5
推荐指数
1
解决办法
3055
查看次数

标签 统计

asp.net-core ×1

asp.net-core-3.0 ×1

dapper ×1

npgsql ×1