Search code examples
dryioc

DryIOC Non-lazy resolution


How can I disable lazy resolution in DryIOC? I need some of my singletons to be instantiated immediately.

At the moment I'm doing all my register calls, and then having another block of resolve calls for the ones I need instantiated in the beginning. But its gettting a bit unwieldy.


Solution

  • You may mark the registrations with specific metadata, let's say with public enum AutoActivate { It }. Then discover the marked registrations and resolve them in preferrable time:

    var container = new Container();
    container.Register<IFoo, Foo>(Reuse.Singleton, setup: Setup.With(AutoActivate.It));
    container.Register<IBar, Bar>(Reuse.Singleton); // don't activate
    
    // when suitable
    var activatedServices = container.GetServiceRegistrations()
        .Where(r => r.Factory.Setup.Metadata is AutoActivate)
        .OrderBy(r => r.FactoryRegistrationOrder)
        .GroupBy(r => r.FactoryRegistrationOrder, (f, r) => r.First())
        .Select(r => container.Resolve(r.ServiceType, r.OptionalServiceKey));