开发者

Singleton or not

I have a windows service running.Inside this service I have hosted some service (WCF). I need to have some kind of a "in memory data holder" class. The purpose of this class is to hold not-persistant data as long as the windows service is running. This class must be accessible thru the WCF services. They put some values in this class or retrieve some values from this class.

First thing what come across my m开发者_Go百科ind was a singleton class.I think this pattern fits perfect for this situation. But then I read some post that the singleton class isnt actually that good.

So is there any alternative for this kind of situation? Or is the singleton for this ok ? What about a Factory method ? But then Where would I find the references for the objcects ?


The Singleton design pattern should really be relabeled as an anti-pattern. It is evil. Don't use it.

A better alternative is to use Dependency Injection (DI) and inject a class which you can use to hold the non-persistent data you need.

A lot of people don't realize that WCF supports Dependency Injection (DI) patterns such as Constructor Injection without too much hassle.

If you scope the injected class as a long-lived object (usually referred to as Singleton lifetime style, but not to be confused with the Singleton design pattern) you can keep accessing the same instance between calls.

However, whenever you use shared objects (whether you use Singleton as a design pattern or a lifetime style) you must be prepared to handle multithreading issues.

Among many other things, this post describes how to inject dependencies into a WCF service implementation when it doesn't have a default constructor.


I'm interested to know why people don't like the singleton, I would happily use it for the above scenario unless someone can tell me some good reasons why not.

Its a simple pattern to understand and implement and I'm thinking keeping it simple is a good thing in 6 months time when you or soemone else has to maintain your code

EDIT Having done some more digging as to why some people don't like the singleton pattern a useful bunch of alternatives is addressed in the question: What's Alternative to Singleton This deals with the unit testing drawbacks of the pattern.

EDIT 2 I'm finally convinced that the singelton can be bad. http://googletesting.blogspot.com/2008/08/by-miko-hevery-so-you-join-new-project.html makes the good point that in terms of maintenance declaring a dependancy at an API level makes it easier for programmers to get a grip on dependancies.


Why would you need a singleton for this?

Do you really have a need to limit instances of this class to a single instance? If not, don't use a singleton - you don't need it and it will only add complexity to your class.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜