1

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

dadhi
  • 4,807
  • 19
  • 25
emdadgar2
  • 820
  • 1
  • 9
  • 15
  • You can define your own scopes the simplest will be to just use names. https://github.com/dadhi/DryIoc/blob/master/docs/DryIoc.Docs/ReuseAndScopes.md#what-scope-is or using child containers - https://github.com/dadhi/DryIoc/blob/master/docs/DryIoc.Docs/KindsOfChildContainer.md#without-singletons – eocron Jun 27 '22 at 20:55
  • @eocron I add example to question, Please recheck (without custom scope) if you have enough time. Thanks – emdadgar2 Jun 27 '22 at 21:11

1 Answers1

0

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;
    }
}
dadhi
  • 4,807
  • 19
  • 25