Possible Valid Use of a Singleton? - c#

I've got to the point in my design, where I am seriously considering a singleton.
As we all know, the "common" argument is "Never do it! It's terrible!", as if we'd littered our code with a bunch of goto statements.
ServiceStack is a wonderful framework. Myself and my team are sold on it, and we have a complicated web-service based infrastructure to implement. I have been encouraging an asynchronous design, and where possible - using SendAsync on the service-stack clients.
Given we have all these different systems doing different things, it occurred to me I'd like to have a common logger, (A web service in itself actually, with a fall-back to a local text file if the web service is not available - e.g. some demons are stalking the building). Whilst I am a big fan of Dependency Injection, it doesn't seem clean (at least, to me) to be passing a reference to a "use this logger client" to every single asynchronous request.
Given that ServiceStack's failure signature is a Func<TRESPONSE, Exception> (and I have no fault with this), I am not even sure that if the enclosing method that made the call in the first place would have a valid handle.
However, if we had a singleton logger at this point, it doesn't matter where we are in the world, what thread we are on, and what part of a myriad of anonymous functions we are in.
Is this an accepted valid case, or is it a non-argument - down with singletons?

Logging is one of the areas which makes sense to be a singleton, it should never have any side-effects to your code and you will almost always want the same logger to be used globally. The primary thing you should be concerned with when using Singletons is ThreadSafety, which in the case of most Loggers, they're ThreadSafe by default.
ServiceStack's Logging API allows you to both provide a substitutable Logging implementation by configuring it globally on App_Start with:
LogManager.LogFactory = new Log4NetFactory(configureLog4Net:true);
After this point every class now has access to Log4Net's logger defined in the Factory above:
class Any
{
static ILog log = LogManager.GetLogger(typeof(Any));
}
In all Test projects I prefer everything to be logged to the Console, so I just need to set it once with:
LogManager.LogFactory = new ConsoleLogFactory();
By default ServiceStack.Logging, logs to a benign NullLogger which ignores each log entry.

There's only one problem with classic implementation of a singleton -
it is easily accessible, and provokes direct use, which leads to strong coupling,
god objects, etc.
under classic implementation I mean this:
class Singleton
{
public static readonly Singleton Instance = new Singleton();
private Singleton(){}
public void Foo(){}
public void Bar(){}
}
If you use singleton only in terms of an object lifecycle strategy,
and let IoC framework manage this for you, maintaining loose coupling -
there is nothing wrong with having 'just one' instance of a class
for entire lifetime of application, as long as you make sure it is thread-safe.

If you are placing that common logging behind a static facade that application code calls, ask yourself how you would actually unit test that code. This is a problem that Dependency Injection tries to solve, but you are reintroducing it by letting application logic depend on a static class.
There are two other problems you might be having. To question I have for you is: Are you sure you don't log too much, and are you sure you aren't violating the SOLID principles.
I've written an SO answer a year back that discusses those two questions. I advice you to read it.

As always, I prefer to have a factory. This way I can change the implementation in future and maintain the client contract.
You could say that singleton's implmenentation could also change but factories are just more general. For example, the factory could implement arbitrary lifetime policy and change this policy over time or according to your needs. On the other hand, while this is technically possible to implement different lifetime policies for a singleton, what you get then should probably not be considered a "singleton" but rather a "singleton with specific lifetime policy". And this is probably just as bad as it sounds.
Whenever I am to use a singleton, I first consider a factory and most of the times, the factory just wins over singleton. If you really don't like factories, create a static class - a stateless class with static methods only. Chances are, you just don't need an object, just a set of methods.

Related

C#: ILogger vs static Log instance

This is more an architectural question:
Do you use ILogger (and pass it in the constructor via DI) or do you prefer a static class Log?
We use ILogger a lot but it really seems to clatter the code especially when it is passed via constructor. If not passed via constructor and just every time created, then I really do not see a benefit if using the interface.
So how do you handle this? I am especially interested in the arguments behind it - not just saying "static" or "interface".
Thx
Using a static instance of anything is a bad idea for different reasons, depending on your use case.
- They are difficult to mock in a unit test so your logger is always writing logs even when they are not needed.
- Lack of mocking also means you cannot write tests to ensure an error log is written in appropriate situations.
- They cannot be replaced at runtime to allow injection of different loggers. This can be important if you are releasing a library for others to use. I define a standard logger interface and log everything to that, then allow clients to inject their own logger as long as it implements my interface.
- If you use the default static Log implementation provided by the vendor, you are locked into their interface meaning you cannot hide or change the surface area of the logger. Changing loggers becomes a MUCH bigger effort if the syntax of the new logger changes.
So that leaves you with some kind of injection. Personally I prefer having all dependencies in the constructor, even if it becomes verbose, because it’s easy to see all dependencies a particular class has. If you are trying to avoid a big constructor you can look into Property Injection. This requires an attribute on a property of the class, but still gives you all the advantages of injecting the dependencies. If you put the injected property on a base class it will be available for all children automatically.
BTW, I’m not a fan of the Ambient Context described above because it’s basically a single purpose DI container, and you must have a concrete reference to multiple ambient service containers. If the easy access of this pattern appeals to you, look into Service Location which is the same idea but more flexible.
If ILogger is really a cross-cutting concern, which is used everywhere and thus just causes to pollute every instance with a new constructor parameter, then what you need is to you use a special way of dependency injection called AmbientContext.
Basically it provides you a singleton Context property, which can be accessed from anywhere in the business scope and contains the "global" dependencies such as logging, time service, etc., whatever you need.
But please note that it doesn't mean you can throw out your ILogger and use a static Log class with a hardcoded implementation. Ambient context is also a way of dependency injection so its dependencies should be resolved.

Dependency injection: single class (WCF service) having multiple dependencies (DB repositories) how to handle?

I've read a book "Dependency injection in .NET" by Mark Seemann and it opened my eyes on many things. But still few question left. Here is one of them:
Let's say we have a WCF service exposing API for working with some database:
public class MyService : IMyService
{
private ITableARepository _reposA;
private ITableARepository _reposB;
//....
public IEnumerable<EntityA> GetAEntities()
{
return _reposA.GetAll().Select(x=>x.ToDTO())
}
public IEnumerable<EntityB> GetBEntities()
{
return _reposB.GetAll().Select(x=>x.ToDTO())
}
//...
}
There may be dozens of repositories service depend on. Some methods use one, some methods another, some methods use few repositories.
And my question is how to correctly organize injection of repository dependencies into service?
Options I see:
Constructor injection. Create a huge constructor with dozens of arguments. Easy for usage, but hard for managing parameters list. Also it's extreemely bad for performance as each unused repository is a waste of resources even if it doesn't use separate DB connection.
Property injection. Optimizes performance, but usage becomes non-obvious. How should creator of the service know which properties to initialize for specific method call? Moreover this creator should be universal for each method call and be located in the composition root. So logic there becomes very complicated and error-prone.
Somewhat non-standard (not described in a book) approach: create a repository factory and depend on it instead of concrete repositories. But the book say factories are very often used incorrectly as a side way to overcome problems that can be resolved much better with proper DI usage. So this approach looks suspicious for me (while achieving both performance and transparency objectives).
Or is there a conceptual problem with this relation 1 to many dependencies?
I assume the answer should differ depending on service instance context mode (probably when it's Single instance, constructor injection is just fine; for PerCall option 3 looks best if to ignore the above warning; for perSession everything depends on the session lifetime: whether it's more close to Single instance or PerCall).
If it really depends on instance context mode, then it becomes hard to change it, because change requires large changes in the code (to move from constructor injection to property injection or to repository factory). But the whole concept of WCF service ensures it is simple to change the instance context mode (and it's not so unlikely that I will need to change it). That makes me even more confused about DI and WCF combination.
Could anyone explain how this case should be resolved correctly?
Create a huge constructor with dozens of arguments
You should not create classes with a huge number of constructor arguments. This is the constructor over-injection code-smell. Having constructors with a huge amount of arguments is an indication that such class does too much: violates the Single Responsibility Principle. This leads to code that is hard to maintain and extend.
Also it's extremely bad for performance as each unused repository is a waste of resources
Have you measured this? The amount of constructor arguments should be mainly irreverent for the performance of the application. This should not cause any noticeable difference in performance. And if it does, it becomes be time to look at the amount of work that your constructors do (since injection constructors should be simple) or its time to switch to a faster DI container if your constructors are simple. Creating a bunch of services classes should normally be blazingly fast.
even if it doesn't use separate DB connection.
The constructors should not open connections in the first place. Again: they should be simple.
Property injection. Optimizes performance
How should creator of the service know which properties to initialize for specific method call
The caller can't reliably determine which dependencies are required, since only constructor arguments are typically required. Requiring properties results in temporal coupling and you lose compile-time support.
Since the caller can't determine which properties are needed, all properties need to be injected and this makes the performance equivalent as with constructor injection, which -as I said- should not be a problem at all.
Somewhat non-standard (not described in a book) approach: create a repository factory and depend on it instead of concrete repositories.
Instead of injecting a repository factory, you could inject a repository provider, a pattern which is better known as the Unit of Work pattern. The unit of work may give access to repositories.
I assume the answer should differ depending on service instance context mode
No, since you should never use the WCF 'Single' mode. In most cases the dependencies you inject into your WCF services are not thread-safe and should not outlive a single request. Injecting them into a singleton WCF service causes Captive Dependencies and this is bad because it leads to all kinds of concurrency bugs.
The core problem here seems that your WCF Service classes are big and violate the Single Responsibily Principle, causing them to hard to create, maintain, and test. Fix this violation by either:
Splitting them up in multiple smaller classes, or
Moving functionality out of them into aggregate services and apply patterns such as the command/handler and query/handler patterns.

Is this a bad use of a static property?

If I have a class with a service that I want all derived classes to have access to (say a security object, or a repository) then I might do something like this:
public abstract class A
{
static ISecurity _security;
public ISecurity Security { get { return _security; } }
public static void SetSecurity(ISecurity security) { _security = security; }
}
public class Bootstrapper
{
public Bootstrapper()
{
A.SetSecurity(new Security());
}
}
It seems like lately I see static properties being shunned everywhere as something to absolutely avoid. To me, this seems cleaner than adding an ISecurity parameter to the constructor of every single derived class I make. Given all I've read lately though, I'm left wondering:
Is this is an acceptable application of dependency injection or am I violating some major design principle that could come back to haunt me later? I am not doing unit tests at this point so maybe if I were then I would suddenly realize the answer to my question. To be honest though I probably won't change my design over that, but if there is some other important reason why I should change it then I very well might.
Edit: I made a couple stupid mistakes the first time I wrote that code... it's fixed now. Just thought I'd point that out in case anyone happened to notice :)
Edit: SWeko makes a good point about all deriving classes having to use the same implementation. In cases where I've used this design, the service is always a singleton so it effectively enforces an already existing requirement. Naturally, this would be a bad design if that weren't the case.
This design could be problematic for a couple of reasons.
You already mention unit testing, which is rather important. Such static dependency can make testing much harder. When the fake ISecurity ever has to be anything else than a Null Object implementation, you will find yourself having to removing the fake implementation on test tear down. Removing it during test tear down prevents other tests from being influenced when you forget to remove that fake object. A test tear down makes your test more complicated. Not that much complicated, but having this adds up when many tests have tear down code and you'll have a hard time finding a bug in your test suit when one test forget to run the tear down. You will also have to make sure the registered ISecurity fake object is thread-safe and won't influence other tests that might run in parallel (test frameworks such as MSTest run tests in parallel for obvious performance reasons).
Another possible problem with injecting the dependency as static, is that you force this ISecurity dependency to be a singleton (and probably to be thread-safe). This disallows for instance to apply any interceptors and decorators that have a different lifestyle than singleton
Another problem is that removing this dependency from the constructor disables any analysis or diagnostics that could be done by the DI framework on your behalf. Since you manually set this dependency, the framework has no knowledge about this dependency. In a sense you move the responsibility of managing dependencies back to the application logic, instead of allowing the Composition Root to be in control over the way dependencies are wired together. Now the application has to know that ISecurity is in fact thread-safe. This is a responsibility that in general belongs to the Composition Root.
The fact that you want to store this dependency in a base type might even be an indication of a violation of a general design principle: The Single Responsibility Principle (SRP). It has some resemblance with a design mistake I made myself in the past. I had a set of business operations that all inherited from a base class. This base class implemented all sorts of behavior, such as transaction management, logging, audit trailing, adding fault tolerance, and.... adding security checks. This base class became an unmanageable God Object. It was unmanageable, simply because it had too many responsibilities; it violated the SRP. Here's my story if you want to know more about this.
So instead of having this security concern (it's probably a cross-cutting concern) implemented in a base class, try removing the base class all together and use a decorator to add security to those classes. You can wrap each class with one or more decorators and each decorator can handle one specific concern. This makes each decorator class easy to follow because they will follow the SRP.
The problem is that is not really dependency injection, even if it is encapsulated in the definition of the class. Admittedly,
static Security _security;
would be worse than Security, but still, the instances of A do not get to use whatever security the caller passed to them, they need to depend on the global setting of a static property.
What I'm trying to say is that your usage is not that different from:
public static class Globals
{
public static ISecurity Security {get; set;}
}

Best way to load website settings once?

I'm still in need of help. I have website settings that I want to load using a singleton pattern. There are so many negatives about using this pattern and every one advices to use Inversion of Control or Dependency Injection. I have not yet worked with IoC or DI.
What is the best way to load website settings once and use it across the whole web application? I thought a singleton pattern would be ideal, but I want to go with best practices. Also, does anyone have any sample code regard using IoC or DI loading website settings? Someone even mentioned that I inject the single's Instance method, but what is the use because it's still a singleton? Also, if anyone has some unit tests regaing this loading of website settings with IoC or DI then it would be appreciated.
I am using C#.
Thanks
Brendan
This is a good thread about it : Good case for Singletons?
Other ones:
Singleton: How should it be used
When should you use the singleton
pattern instead of a static
class?
Singletons: good design or a
crutch?
On Design Patterns: When to use the
Singleton?
Singleton is fine in this case if it makes sense to have an instance. Generally it doesn't, and you can just use a static.
Much of the downside of singletons and statics don't exist if they're immutable (those downsides relating to side-effects in global state).
The important thing here is that conceptually, you are looking at the application settings each time you use them. Doing this through a singleton or static just adds a performance boost. If immutability is used to make this impossible to change afterwards, then the only difference between that and looking up the settings each time, is that performance boost.
Conceptually therefore, you aren't introducing global state, you are just improving the performance of global state that already exists. Hence you haven't made things any worse.
Even some who are adamant against global objects (whether singleton or static) make an exception with the flow is one way. Global logging is one-way as the other classes only ever write to it, never read. Global settings are one-way as the other classes only ever read from them, never write.
There are a couple of options, you can use a simple static class :
public class ConfigurationBase
{
public static string Something
{
get { return ConfigurationManager.AppSettings["Something"]; }
}
// ....
}
Or try the Castle Dictionary Adapter :
http://codebetter.com/blogs/benhall/archive/2010/07/22/improving-testability-with-the-castle-dictionary-adapter.aspx
Depending on your needs. It's not necessary to over engineer. Keep it simple and readable first.

In what circumstances should I use a Singleton class?

Closed as exact duplicate of this question. But reopened, as the other Singleton questions are for general use and not use for DB access
I was thinking of making an internal data access class a Singleton but couldn't convince myself on the choice mainly because the class has no state except for local variables in its methods.
What is the purpose of designing such classes to be Singletons after all?
Is it warranting sequential access to the database which is not convincing since most modern databases could handle concurrency well?
Is it the ability to use a single connection repeatedly which could be taken care of through connection pooling?
Or Is it saving memory by running a single instance?
Please enlighten me on this one.
I've found that the singleton pattern is appropriate for a class that:
Has no state
Is full of basic "Service Members"
Has to tightly control its resources.
An example of this would be a data access class.
You would have methods that take in parameters, and return say, a DataReader, but you don't manipulate the state of the reader in the singleton, You just get it, and return it.
At the same time, you can take logic that could be spread among your project (for data access) and integrate it into a single class that manages its resources (database connections) properly, regardless of who is calling it.
All that said, Singleton was invented prior to the .NET concept of fully static classes, so I am on the fence on if you should go one way or or the other. In fact, that is an excellent question to ask.
From "Design Patterns: Elements Of Reusable Object-Oriented Software":
It's important for some classes to
ahve exactly one instance. Although
there can be many printers in a
system, there should only be one
printer spooler. There should only be
one file system and one window
manager. ...
Use the Singleton pattern when:
there must be exactly one instance of a class, and it must be accessible to clients from a well-known access point
the sole instance should be extensible by subclassing and clients should be able to use an extended instance without modifying their code
Generally speaking, in web development, the only things that should actually implement Singleton pattern are in the web framework itself; all the code you write in your app (generally speaking) should assume concurrency, and rely on something like a database or session state to implement global (cross-user) behaviors.
You probably wouldn't want to use a Singleton for the circumstances you describe. Having all connections to a DB go via a single instance of a DBD/DBI type class would seriously throttle your request throughput performance.
The Singleton is a useful Design Pattern for allowing only one instance of your class. The Singleton's purpose is to control object creation, limiting the number to one but allowing the flexibility to create more objects if the situation changes. Since there is only one Singleton instance, any instance fields of a Singleton will occur only once per class, just like static fields.
Source: java.sun.com
using a singleton here doesn't really give you anything, but limits flexibility
you WANT concurrency or you won't scale
worrying about connections and memory here is a premature optimization
As one example, object factories are very often good candidates to be singletons.
If a class has no state, there's no point in making it a singleton; all well-behaved languages will only create, at most, a single pointer to the vector table (or equivalent structure) for dispatching the methods.
If there is instance state that can vary among instances of the class, then a singleton pattern won't work; you need more than one instance.
It follows, then, by exhaustion, that the only cases in which Singleton should be used is when there is state that must be shared among all accessors, and only state that must be shared among all accessors.
There are several things that can lead to something like a singleton:
the Factory pattern: you construct
and return an object, using some
shared state.
Resource pools: you have a shared
table of some limited resources,
like database connections, that you
must manage among a large group of
users. (The bumpo version is where
there is one DB connection held by
a singleton.)
Concurrency control of an external
resource; a semaphore is generally
going to be a variant of singleton,
because P/V operations must
atomically modify a shared counter.
The Singleton pattern has lost a lot of its shine in recent years, mostly due to the rise of unit testing.
Singletons can make unit testing very difficult- if you can only ever create one instance, how can you write tests that require "fresh" instances of the object under test? If one test modifies that singleton in some way, any further tests against that same object aren't really starting with a clean slate.
Singletons are also problematic because they're effectively global variables. We had a threading issue a few weeks back at my office due to a Singleton global that was being modified from various threads; the developer was blinded by the use of a sanctioned "Pattern", not realizing that what he was really creating was a global variable.
Another problem is that it can be pathologically difficult to create true singletons in certain situations. In Java for example, it's possible to create multiple instances of your "singleton" if you do not properly implement the readResolve() method for Serializable classes.
Rather than creating a Singleton, consider providing a static factory method that returns an instance; this at least gives you the ability to change your mind down the road without breaking your API.
Josh Bloch has a good discussion of this in Effective Java.
You have a repository layer that you want created once, and that reference used everywhere else.
If you go with a standard singleton, there is a bad side effect. You basically kill testability. All code is tightly couple to the singleton instance. Now you cannot test any code without hitting the database (which greatly complicates unit testing).
My advice:
Find an IOC that you like and integrate it into your application (StructureMap, Unity, Spring.Net, Castle Windsor, Autofac, Ninject...pick one).
Implement an interface for you repository.
Tell the IOC to treat the repository as a singleton, and to return it when code is asking for the repository by the interface.
Learn about dependency injection.
This is a lot of work for a simple question. But you will be better off.
with c#, I would say that a singleton is rarely appropriate. Most uses for a singleton are better resolved with a static class. Being mindful of thread safety is extremely important though with anything static. For database access, you probably don't want a single connection, as mentioned above. Your best bet is to create a connection, and use the built in pooling. You can create a static method that returns a fresh connection to reduce code, if you like. However an ORM pattern/framework may be better still.
In c# 3.5 extension methods may be more appropriate than a static class.

Categories