开发者

Making Database-Class static?

开发者 https://www.devze.com 2023-04-04 19:06 出处:网络
I\'m currently having a Class named \"SqlData\", which contains all the Methods needed to Connect to my MS-SQL Database.

I'm currently having a Class named "SqlData", which contains all the Methods needed to Connect to my MS-SQL Database.

It contains methods for Inserting, Deleting and Updating different kinds of tables - and therefore is开发者_运维技巧 used in many Windows of my WPF application.

Let's say that nearly 90% of my WPF-Windows are calling at least three Methods of my SqlData Methods for Loading, Inserting and Updating different records...

At the moment, I need to instantiate my Sql-Class in every Window - therefore I'm thinking of making the entire Class static so I don't need to instantiate it every time?

But also I've read not to use static classes while communicating with external Servers like WebServices or Databases.

Could you give me any advice on how I should go on?

Following a few Methods used in my Class (bool returns true, when the statement completed, otherwise false):

public DataTable GetAllSomething(DataTable _data)

public bool WriteSomething(Object something, out int insertedId)

public bool DeleteSomething(Object something)

Thank you!


At the moment, I need to instantiate my Sql-Class in every Window - therefore I'm thinking of making the entire Class static so I don't need to instantiate it every time?

The time taken to instantiate a class in .NET is so ridiculously low that you should not be worried about. Personally I don't use static classes because they introduce strong coupling between the different layers of an application making them more difficult to unit test in isolation.

So I prefer to abstract all database access behind an interface (or abstract class) and then provide an implementation of this interface against a specific database.


Just do not do it, it's ok to create an instance of your class every time it is needed, there is nothing wrong with that.

even if you are not doing it yet right now, you could imagine to use some kind of Dependency Injection soon in the future, or you could write unit tests with any testing framework available in .NET and in general you will have much more options with no static classes.


I always create a database object at the beginning of my app and pass it with the constructors of all windows and classes which need it. It gives me the ability to add data to it, like a connectionstring, which is only needed in the beginning, and there's not a chance methods are being called before the databaseconnection has been set up (as can be with static) because that's done in the constructor.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号