2

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>() )
{
  // ...
}
Mooh
  • 744
  • 5
  • 25

1 Answers1

1

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.

dadhi
  • 4,807
  • 19
  • 25
  • I was hoping to create something like weak reference. Imagine there is a resource singleton registered in the container, and another interface intended to control the resource. Client code may request resource control to carry out high level operations without knowing whether resource is really created. If not, all methods of the control would do nothing. The point it that resource is expensive and optional, and only required if some other service in the container creates it. – Mooh Dec 15 '17 at 16:03
  • Thanks for clarification. After a bit of thinking the feature indeed is possible using decorator and factory method. Updated my answer. – dadhi Dec 16 '17 at 17:36