我必须在我的所有控制器中为ConnectionString使用“IConfiguration”。我还必须在我的DAL中发送它。
我想制作一个通用的DAL(数据访问层)并在其他DAL中继承它。
其实我不想用EF(实体框架)
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
}
}
你基本上问的是如何使用外部化配置而不实际外化它。如果该陈述的逻辑(或缺乏)不明显,那么您想要的是不可能的。
在各种类和/或项目之间共享任何东西的方法是一个类,很可能是在类库中。如果您愿意,可以创建一个静态“常量”类来保存您的连接字符串:
public static class Constants
{
public const string ConnectionString = "foo";
}
然而,这就是所谓的“反模式”。换句话说,这是你不应该做的事情。特别是对于连接字符串这样的东西,往往需要根据环境而变化,这对于像这样的静态类很难实现。您还有保护此字符串的问题,因为您的应用程序可以轻松地反编译以显示它,以及用于访问数据库的用户名和密码。如果你正在考虑SecureString
,那将无法在这里工作。原始的字符串文字仍然容易受到攻击,即使你试图用它制作一个SecureString
。
简而言之,外部化配置是外部化的原因。它允许为应用程序提供所需的信息,而无需将该信息紧密地耦合到您的应用程序。您可以随意切换,重要的是,使用安全存储机制来保护静态信息。
更重要的是,像DAL这样的东西应该是抽象的。即使您通常是为特定应用程序创建它,它也应具有一定程度的可重用性。如果将连接字符串绑定到它,则它会紧密耦合到该特定域,这通常是一个糟糕的设计。
长和短,保持配置所属的位置:在应用程序级别和外部化。
您可以创建一个静态类,并使用它在您需要的地方轻松访问DAL实现。