The apparent answer would be using a
singleton design pattern.
However, I don't want to present this opportunity as a perfect solution. First of all, this is not the best design pattern. It is quite possible to work without singletons even when you need to have some unique objects per application. The idea is: you can create some unique object as a local (stack) variable in your entry-point method (
Main
) and pass the reference to it in a chain to all other objects. It seems to be more bothersome than the singleton-based techniques, but can be more reliable. For example, you won't accidentally use it in non-UI threads and won't create cross-thread problems.
More importantly,
System.Windows.Forms
already provides a singleton,
Application
object. However, using its derived class would be inconvenient, by some pretty obvious reasons. You can uses another unique object of the type you need to derive from the .NET FCL class anyway — main form (you derive its class from the class
Form
). As this class is "de-facto" unique (unless you call
Application.Run
more than once, with different forms), you can put all unique database facilities in this class.
Moreover, for a really clean application design, you can develop a separate interface type which provides all this database functionality and implement this interface by your main form. To use it "anywhere in application", you can pass the interface instance to other forms and other objects, not the reference to the form. It will provide abstraction from the UI functionality present in form classes and yet provide a reference to a unique object, which is your form. (I hope you understand that the interface reference will serve as a
compile-time type passed to all the parts of your application code, but the
runtime type
of the passed object will still be some form, only form-specific members will be not accessible to the code using the interface instance; which will perfectly suit your goals.)
Another aspect of this problem is isolation of the UI from other aspects of the application. In practice, you have to have separate UI layer, data layers, and other layers, such as "business logic". So, let's take a deeper look at the problems related to your question. I suggest you learn and analyze applicability of the following
architectural patterns (
http://en.wikipedia.org/wiki/Architectural_pattern_(computer_science)[
^]):
MVVM — Model View View Model,
http://en.wikipedia.org/wiki/Model_View_ViewModel[^],
MVC — Model-View-Controller,
http://en.wikipedia.org/wiki/Model-view-controller[^]),
MVA — Model-View-Adapter,
http://en.wikipedia.org/wiki/Model–view–adapter[^],
MVP — Model-View-Presenter,
http://en.wikipedia.org/wiki/Model-view-presenter[^].
Pay attention for the motivation of those architectures. If you understand it, you would be able to create better design ideas.
—SA