开发者

Static objects in wpf app

开发者 https://www.devze.com 2022-12-19 17:49 出处:网络
In m开发者_如何学运维y wpf app i am using a lot of objects declared as static for caching purposes.

In m开发者_如何学运维y wpf app i am using a lot of objects declared as static for caching purposes. Just wondering if there are any drawbacks.


I almost never use static data, because of the inherent problems that come into play when you add worker threads.

If you only want one instance of something accessible by your objects, then perhaps the Singleton pattern will help. You might want to read this helpful article on Singletons in C#.

There's also a framework available that makes requesting services really easy. You can set up the Framework to give you a new instance of a service, or the same service every time. The problem is that I can't remember what it's called, and would really appreciate it if someone else could comment on this because I'd like to read up on it again. I thought it was Unity or Prism, but I'm not sure. I know the latter framework is for setting up your application with MVVM principles in mind.


One disadvantage is that a static members on a class don't have full lazy instantiation. The static constructor will be run the first time any member on that class is accessed. This may or may not be a big concern for you.

A much bigger problem, in my opinion, is that statics are not good for unit testing. Say you are trying to write unit tests for another class, that reference those static objects. You have no way of setting up a mock for those objects. You're forced to use the real thing, which may end up forcing you to start up a large part of your system, in which case it's no longer a unit test, but an integration test.

I don't think you need to avoid the static keyword entirely; just be aware of the limitations you're putting on your program by doing so. And using a Singleton is not the only alternative. You may simply just choose to follow the "just create one" policy. :)

0

精彩评论

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

关注公众号