【发布时间】:2019-03-28 12:25:07
【问题描述】:
我必须在我的所有控制器中为 ConnectionString 使用“IConfiguration”。 而且我还必须在我的 DAL 中发送它。
我想做一个通用的DAL(数据访问层)并在其他DAL中继承。
其实我不想用EF(entity framework)
public class UserController : Controller
{
public string ConnectionString { get; set; }
private readonly IConfiguration configuration;
public UserController(IConfiguration config)
{
this.configuration = config;
ConnectionString = configuration.GetConnectionString("DefaultConnection");
}
public IActionResult ViewProfile()
{
UserControllerGateway userControllerGateway = new UserControllerGateway();
UserProfileModel userProfile = new UserProfileModel();
userProfile = userControllerGateway.ViewProfile(ConnectionString);//I have to send connectionString to my DAL
return View(userProfile);
}
///DAL
public class CommonGateway
{
public string ConnectionString { get; set; }
public SqlConnection Connection { get; set; }
public SqlCommand Command { get; set; }
public string Query { get; set; }
public SqlDataReader Reader { get; set; }
public CommonGateway()
{
ConnectionString = " "; //What can I do here
}
}
【问题讨论】:
-
为什么不直接在 DAL 或 DAL 的基类中使用和访问 IConfiguration 抽象?
-
确实,配置功能已经在 .NET Core 中可用。无需添加另一个抽象。至于
CommonGateway,它看起来像一个错误,它会使连接保持打开的时间比需要的时间长,从而损害性能并由于阻塞而增加延迟。数据访问服务类应该只在需要的地方创建连接并尽快关闭它们。连接的范围应该大于它们使用的方法 -
应该在控制器中注入数据访问服务类,而不是连接字符串。数据类可能依赖于
IConfiguration。另一种选择是在注册期间使用工厂方法读取连接字符串并将其作为参数传递给类的构造函数 -
@PanagiotisKanavos 看起来像是一个错字“连接应该不的范围大于它们所使用的方法”
标签: c# asp.net-mvc model-view-controller asp.net-core-2.0 connection-string