Quantcast
Viewing all articles
Browse latest Browse all 4

Answer by Euphoric for How should I refactor a singleton (to be used by a container) when the refactored class requires initialization and takes a dependency?

Not sure what language you are using, so I'm using pseudo-C# as example.

You can create an IInitializes interface, which you then call after the instances are created.

public interface IInitializes{   void Initialize();}public class PreviousSingleton : IPreviousSingleton, IInitializes{    IDependency dep;    public PreviousSingleton(IDependency dep)    {        this.dep = dep;    }    public void Initialize() {        // do whatever with dep    }}

Then when you register and create it using IoC :

IoC ioc;ioc.RegisterAsSingleton<PreviousSingleton>(); // make sure IoC recognizes it as both having IPreviousSingleton and IInitializes interfaces// do rest of the registrations// and after registrations are done, run initializationvar instancesToInitialize = ioc.GetAllInstances<IInitializes>();foreach(var inst in instancesToInitialize){    inst.Initalize();}var noLongerSingleton = ioc.GetInstance<IPreviousSingleton>(); // should be initialized now

This works, because only one instance will be kept inside IoC, which means same instance will be initialized as one that will be passed to other objects. Also works if you have multiple different classes implementing IInitializes.


Viewing all articles
Browse latest Browse all 4

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>