So, I’m writing a fairly complex C# application right now, that uses MySQL as the database system. I’m wondering, what would be the best way to use MySQL through the entire program? Creating static functions so you can use it everywhere? Refering to a SQLHandler class, which does all the communication?
Thanks!
I would abstract the data access functions inside an interface which could act as a data access layer. Then have an implementation working with MySQL. Then always pass the interface to other layers of your application that need to query the database. This way you get weak coupling between those layers and make unit testing in isolation of those layers possible.
Let’s have an example. Suppose that you have a
Productmodel:Now you could define a repository which will abstract the operations you need to perform with this model:
and then you could have an implementation of this interface working with MySQL:
Now every layer of your application which needs to work wit products could simply take the
IProductRepositoryas constructor parameter and call the various CRUD methods.It is only inside the composition root of your application where you would wire the dependencies and specify that you would be working with a
MySQLProductRepository. Ideally the instance of this repository should be a singleton.You might also checkout popular ORMS such as NHibernate, Entity Framework, Dapper, … to simplify the implementation of the various CRUD operations inside your repositories and perform the mapping to the domain models. But even if you decide to use an ORM framework it is still good practice to separate the concerns into different layers in your application. This is very important when designing complex applications if you want they to remain maintainable.