Search code examples
dryioc

Resolution status in DryIoc container


Is it possible in DryIoc container to figure out whether some singleton has been instantiated?

For instance

var container = new Container();
container.Register<IApplicationContext, ApplicationContext>( Reuse.Singleton );

// var context = container.Resolve<IApplicationContext>(); 

if ( container.IsInstantiated<IApplicationContext>() ) // Apparently this does not compile
{
  // ...
}
// OR
if ( container.IsInstantiated<ApplicationContext>() )
{
  // ...
}

Solution

  • There is no way at the moment and no such feature planned. You may create an issue to request this.

    But I am wandering why it is needed. Cause singleton provides a guarantee to be created only once, so you may not worry or check for double creation.

    Is it for something else?

    Update

    OK, in DryIoc you may register a "decorator" to control and provide information about decoratee creation, here is more on decorators:

    [TestFixture]
    public class SO_IsInstantiatedViaDecorator
    {
        [Test]
        public void Test()
        {
            var c = new Container();
            c.Register<IService, X>(Reuse.Singleton);
    
            c.Register<XProvider>(Reuse.Singleton);
    
            c.Register<IService>(
                Made.Of(_ => ServiceInfo.Of<XProvider>(), p => p.Create(Arg.Of<Func<IService>>())),
                Reuse.Singleton,
                Setup.Decorator);
    
            c.Register<A>();
    
            var x = c.Resolve<XProvider>();
            Assert.IsFalse(x.IsCreated);
    
            c.Resolve<A>();
    
            Assert.IsTrue(x.IsCreated);
        }
    
        public interface IService { }
        public class X : IService { }
    
        public class A
        {
            public A(IService service) { }
        }
    
        public class XProvider
        {
            public bool IsCreated { get; private set; }
            public IService Create(Func<IService> factory)
            {
                IsCreated = true;
                return factory();
            }
        }
    }
    

    This example also illustrates how powerful is composition of DryIoc decorators and factory methods.