【发布时间】:2020-11-05 05:45:12
【问题描述】:
对 DI 和概念非常陌生,因此我正在努力寻找解决以下问题的方法:
我们有一个 Web 项目(MVC,Core 3)和一个类库(用于所有业务和数据层)。我们试图在类库中有一个 DBContext 类来处理所有数据库连接(使用连接字符串)。我们可以将 IConfiguration 注入到这个 DBContext 中,这样我们就可以从中提取连接字符串并将其放入本地只读字符串中。我们有一个方法可以使用这个连接字符串返回 SQL 连接。
问题是当我们在业务类中时,我们需要访问 DBContext 类来获取 SQL Connection 对象。我们无法创建“新”DBContext,因为我们在其他业务类中没有 IConfigration。
DBContext 类库:
public class DBContext
{
private readonly string _connectionString;
private readonly IConfiguration _configuration;
public DBContext(IConfiguration configuration)
{
_configuration = configuration;
_connectionString = configuration.GetConnectionString("db");
}
public SqlConnection Connection()
{
return new System.Data.SqlClient.SqlConnection(_connectionString);
}
}
所以问题出在我们查看类库中的 Customer 类时:
客户类别:
public class Customer
{
public int CustomerId { get; set; }
public string CustomerName { get; set; }
public Customer(int customerId)
{
//load customer from the db from the id
using (IDbConnection db = new DBContext().Connection())
{
//call SQL Stored Procedure here ....
}
}
}
我们无法创建“新”DBContext 来访问连接,因为在 Customer 类中我们没有要传递给构造函数的 IConfiguration 对象。
我们如何以“正确”的方式实现这一目标?
是否像必须将 IConfiguration 对象 DI 到每个类库构造函数中一样糟糕,例如来自所有 Web 控制器的客户,所以我们可以将其传递给 DBContext?因为这看起来很啰嗦。
对不起,如果这是非常基本的 DI 东西,但只是在努力寻找如何做这些东西的好例子。
提前致谢,
罗
【问题讨论】:
-
如果您的 Customer 类与数据库本身一起工作,则必须将依赖项注入其中才能与数据库一起工作。注意:它可以只是一个连接字符串,而不是 IConfiguration。
-
一般来说,要遵守 SOLID 原则,Customer 类必须只执行业务逻辑。存储库类应该与数据库一起使用。
标签: asp.net asp.net-core dependency-injection