Search code examples
c#dryioc

Check an service created before in DryIoC


How to check a service created before in current scope in DryIoC?

I want to prevent create a service, if already isn't created using dryioc.

I want a function like IsResolved in this example:

    container.Register<S>();
    if (container.IsResolved<S>()==true){ //always false
      //Do any thing
     }
    var s = container.Resolve<S>();
    if (container.IsResolved<S>()==true){ //always true
      //Do any thing
     }

Note: IsResolved not found in DryIoC


Solution

  • You may register the decorator that stores the flag IsResolved:

    [Test]
    public void Using_decorator_to_implement_IsResolved()
    {
        var c = new Container();
    
        c.Register<Abc>();
    
        var d = new AbcDecorator();
        c.RegisterDelegate<Abc, Abc>(a => d.Decorate(a), setup: Setup.Decorator);
    
        Assert.IsFalse(d.IsResolved);
    
        var abc = c.Resolve<Abc>();
        Assert.IsNotNull(abc);
    
        Assert.IsTrue(d.IsResolved);
    }
    
    class Abc {}
    class AbcDecorator 
    {
        public bool IsResolved { get; private set; }
        public Abc Decorate(Abc a)
        {
            IsResolved = true;
            return a;
        }
    }