Possible Duplicate:
Is it better to create a singleton to access unity container or pass it through the application?
I am introducing IoC container into the system. The natural question is, should it be a singleton or an instance passed to a class to use? I lean towards having it as a singleton instance because:
- No need to clutter class definition like constructors, additional properties.
- Clearer - one instance per application, one initialization routing.
- Ability to have default mapping with overrides if necessary (like for unit testing).
Here is how it looks:
class Main
{
public static void main(params string[] args)
{
IoCContaner.Intance.Add<IBar>();
IoCContaner.Intance.Add<IBaz>();
IoCContaner.Intance.Add<IQux>();
var foo = new Foo();
Foo.DoBarStuff();
}
}
class Bar : IBar
{
public Bar(IBaz, IQuz) {}
public void DoBazStuff() { _baz.DoStuff(); }
}
class Foo
{
public void DoBarStuff()
{
var bar = IoCContaner.Intance.Resolve<IBar>();
bar.DoBazStuff();
}
}
Is there anything I am missing and instead I should actually have something like:
class Foo
{
IoCContainer _c;
public Foo(IoCContainer c) { _c = c; }
...
private void DoBarStuff()
{
var bar = _c.Resolve<IBar>();
bar.DoBazStuff();
}
}
Of course with the second approach I may always to fall back to the first one by passing around a singleton container instance.
EDITED: updated code examples