从 app.config 注入连接字符串与从 BaseDataProvider 类读取它
您是否看到从 Global.asax.cs 注入数据库连接字符串有什么好处 ASP.NET MVC 中的类与从访问 app.config 文件的 BaseDataProvider 类读取连接字符串的方法相比?
Do you see any benefit in injecting the database connnection string from the Global.asax.cs
class in ASP.NET MVC compared to the method in reading the connection string from a BaseDataProvider class accessing the app.config file?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我更愿意使用构造函数注入来注入所需的任何对象(只要可能)。
我看到的一个小优点是类依赖关系的透明度。
例如,如果您尝试在测试工具中实例化一个类(在进行集成测试时):
ConnectionString
属性更新:
构造函数注入方法的另一个优点是它将类本身与从 app.config 获取连接字符串的机制分离。
这可能会在您现在甚至没有想到的未来场景中实现。
例如,在我当前从事的一个项目中,我有一个具有数据库访问权限的组件,并且我在多个上下文中重用了它。在其中一些中,它使用来自配置文件的标准连接字符串,而在其他中,我有另一个组件,可以根据某些条件决定使用哪个连接字符串。
如果您采用第二种方法,则需要更改代码才能支持此类功能。
I'd prefer to inject any objects needed using constructor injection (whenever possible).
One small advantage I see is transparency regarding a class's dependencies.
For example, if you try to instantiate a class in a test harness (while doing integration testing):
ConnectionString
property being setUpdate:
Another advantage of the constructor injection approach is that it decouples the class itself from the mechanism of getting the connection string from the app.config.
This could enable in the future scenarios that you don't even think about right now.
For example, in a project I currently work on I have a component that has db access and I have reused it in several contexts. In some of them it uses a standard connection string coming from the config file, while in others I have another component that decides which connection string to use based on some conditions.
If you go for the second approach, you'll need to change the code in order to support such a functionality.
我通常采用混合方法,这样我的 BaseDataProvider 类有一个空的构造函数,它默认为配置中存储的任何内容,但在我需要默认连接以外的连接的情况下,会被重写以接受 connString 。
然后我的 Global.asax 类包含必要的逻辑来确定在给定情况下他们可能需要什么连接字符串。例如,假设您的 Web 应用程序部署在世界各地的服务器上,您希望连接到最近的可用数据库服务器以避免延迟问题。因此,在用户登录时,我会找出我的用户在哪里,然后使用适当的连接对其进行设置
I usually take a hybrid approach such that my BaseDataProvider class has an empty constructor which defaults to whatever is stored in the config, but is overriden to accept a connString for cases where I need a connection other than the default.
Then my Global.asax class contains the necessary logic to determine what connection string they might need in a given situation. For example, say you have your web application deployed internationally on servers all over the world, you'd want to connect to the nearest available db server to avoid latency issues. So on user login, I would figure out where my user was and then set them up with the appropriate connection