数据库访问来自世界各地的应用 [英] Database access from everywhere in application
问题描述
如果我想在Delphi中访问数据库,我可以一个数据模块添加到项目中,从我的MainForm的配置,然后在任何地方访问它的应用;一个引用将被存储在一个全局变量。
If I wanted to access a database in Delp I could add a datamodule to a project, configure it from my mainform and then access it anywhere in the application; a reference would be stored in a global variable.
我知道,在C#和其他更现代的面向对象语言的全局变量是令人难以接受的。那么,怎样才能从我访问我的数据库,我需要它吗?我最大的问题是配置:位置,用户,密码等是在设计时未知
I know that in C# and other more modern OO languages global variables are frowned upon. So how can I access my database from where I need it? The biggest problem I have is the configuration: location, user, password, etc. are unknown at design time.
我现在有一个分贝级,并作出新的实例当我需要它,但我将不得不存储在全局访问的东西的设置,我只是提出这个问题。
I now have a db-class and make a new instance when I need it, but then I would have to store those settings in some globally accessible thing, and I have simply moved the problem.
什么是标准的解决方案?
What's the standard solution?
感谢,问候,米尔。
推荐答案
在我看来,你需要创建一个合适的对象(包含连接或类似),该实例传递到的每个对象需要访问的(见的依赖注入)
It seems to me that you need to create an appropriate object (containing the connection or similar), and pass that instance to each object requiring access (see dependency injection)
这是使用不同的单身。通过这种机制,它会从依赖一个对象以及(也许在这种情况下更令人信服的理由),让你在的地方原来注射的数据库访问对象的注入模拟对象或类似的执行测试自由你。我肯定会回避此方案中的单机制了。
This is different from using singletons. By using this mechanism, it'll free you from the dependency on one object and (perhaps a more compelling reason in this instance) allow you to perform testing by injecting mock objects or similar in place of the originally-injected database accessor object. I would definitely shy away from the singleton mechanism in this scenario.
这篇关于数据库访问来自世界各地的应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!