Is it possible to use Singleton?

I have a point in my design where I seriously consider singleton.

As we all know, the “common” argument is “Never do it! It's awful!” As if we had tortured our code with a bunch goto.

ServiceStack is a great structure. My team and I are sold on it, and we have a complex infrastructure based on web services. I encourage asynchronous design and, where possible, with the help of a SendAsyncstack service on clients.

Given that we have all these different systems that do different things, it occurred to me that I would like to have a common registrar (the web service itself is actually, with a return to the local text file, if the web service is not available - for example, some demons are chasing a building). Although I am a big fan of Injection Dependency Injection, it seems to me not clean (at least to me) to pass a link to "use this client-registrar" to every asynchronous request.

Given that the ServiceStack failure signature is Func<TRESPONSE, Exception>(and I have no problem with that), I'm not even sure if the enable method that made the call in the first place would have a valid handle.

However, if at that moment we had a single logger, it does not matter where we are in the world, what stream we are in, and what part of the myriad of anonymous functions in which we are.

Is this a valid valid case, or is it not an argument - down with single dots?

+5
source share
4 answers

Registration is one area that makes sense to be a single, it should not have any side effects for your code, and you almost always want the same registrar to be used globally. The main thing you should deal with when using Singletons is ThreadSafety, which, in the case of most Loggers, is ThreadSafe by default.

ServiceStack Logging API Logging, App_Start

LogManager.LogFactory = new Log4NetFactory(configureLog4Net:true);

log4Net logger, Factory :

class Any
{
    static ILog log = LogManager.GetLogger(typeof(Any));
}

, ,

LogManager.LogFactory = new ConsoleLogFactory();

ServiceStack.Logging NullLogger, .

+3

singleton - , , ..

:

class Singleton
{
   public static readonly Singleton Instance = new Singleton();
   private Singleton(){}
   public void Foo(){}
   public void Bar(){}
}

singleton , IoC framework , - , " " , , .

+3

, , , unit test . , Dependency Injection , , .

, . , , : , , SOLID.

, . .

0

, factory. , .

, , . , factory . , , , , , , "singleton", "singleton ". , , , .

Whenever I use singleton, I first look at the factory and most of the time, the factory just wins over singleton. If you really don't like factories, create a static class - a stateless class with static methods. Most likely, you just do not need an object, just a set of methods.

0
source

All Articles