An injection of addiction is your friend. As already mentioned, expose the dependency through the constructor (which seems to be a typical way), or you can do it through Property injection. Anyway, when you register your dependency on application launch, you can tell the container to make it a single, so when you request a link, you get the same effect as a static link.
For Ninject, the syntax is:
var kernel = new Ninject.StandardKernel(settings); kernel.Bind<ISomeInterface>().To<MyConcreteObject>().InSingletonScope();
For Unity, the syntax is:
UnityContainer container = new UnityContainer(); container.RegisterType<ISomeInterface, MyConcreteObject>(new ContainerControlledLifetimeManager());
So your classes might be something like this:
public class MyThing { ISomeInterface _mySingletonObject; public MyThing(ISomeInterface mySingletonObject) { _mySingletonObject = mySingletonObject; } }
This class will always have the same instance of the object into which it was entered if you use a container to resolve an instance of this class.
Again, for Ninject:
var singletopnObject = kernel.Get<ISomeInterface>();
And unity (I think from memory)
var singletopnObject = container.Resolve<ISomeInterface>();
And all other IoC containers offer the same features in different ways.
PS Statics are not evil. They are fast and very useful when used properly.
source share