单身与否单身

2023-09-02 10:55:54 作者:浅陌初心.

我有一个窗口服务running.Inside这项服务,我已经接待了来访的服务(WCF)。 我需要有某种内存中的数据持有级。这个类的目的是,只要Windows服务运行时用来保存未持续性数据。 这个类必须能够访问直通的WCF服务。他们把一些价值在这个类或检索某些值从这个类。

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.

第一件事是什么碰到我的脑海里是一个单class.I觉得这个模式适合最适合这种情况。但后来我看了一些帖子说的单例类心不是真正的好。

First thing what come across my mind 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.

那么,有没有替代这种情况?或者是单身这个好不好?怎么样一个工厂方法?但随后我会在哪里找到的objcects的参考?

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 ?

推荐答案

Singleton设计模式应该被重新标记为一个反模式。 这是邪恶。不要使用它。

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

一个更好的选择是使用依赖注入(DI)和注入类,你可以用它来抱你所需要的非持久性数据。

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.

很多人没有意识到,WCF支持依赖注入(DI)的模式,如构造器注入没有太多的麻烦。

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

如果您范围注入类作为一个长期存在的对象(通常简称为单身的终身风格的,但不要与Singleton设计模式混淆),你可以使访问的同一个实例呼叫。

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.

不过,只要您使用共享对象(无论是否使用辛格尔顿作为一种设计模式,还是一辈子的风格),你必须ppared处理的多线程问题$ P $

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.

在许多其他事情,this帖子描述了如何把依赖注入WCF服务的实现时,它不会有一个默认的构造函数。

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