Alex Rivera | Logout

How to implement a singleton in C#?

Asked 2008-10-29T13:04:38.913
31

How do I implement the singleton pattern in C#? I want to put my constants and some basic functions in it as I use those everywhere in my project. I want to have them 'Global' and not need to manually bind them every object I create.

Edit
Report

2 Answers

3

Static singleton is pretty much an anti pattern if you want a loosely coupled design. Avoid if possible, and unless this is a very simple system I would recommend having a look at one of the many dependency injection frameworks available, such as http://ninject.org/ or http://code.google.com/p/autofac/.

To register / consume a type configured as a singleton in autofac you would do something like the following:

var builder = new ContainerBuilder()
builder.Register(typeof(Dependency)).SingletonScoped()
builder.Register(c => new RequiresDependency(c.Resolve<Dependency>()))

var container = builder.Build();

var configured = container.Resolve<RequiresDependency>();

The accepted answer is a terrible solution by the way, at least check the chaps who actually implemented the pattern.

answered 2008-10-29T14:43:21.867
1

Personally I would go for a dependency injection framework, like Unity, all of them are able to configure singleton items in the container and would improve coupling by moving from a class dependency to interface dependency.

answered 2008-10-30T11:37:06.000

Your Answer