How to prevent DryIoc to dispose singletons on child container dispose

397 views Asked by At

I want to use child container from DryIoc, but somehow it is disposing singletons from parent container. How can I create child container which resolves the singleton instances, but does not dispose them?

    [Test]
    public void Test1()
    {
        IService service;
        using (var parent = new Container())
        {
            parent.Register<IService, Service>(Reuse.Singleton);
            service = parent.Resolve<IService>();
            using (var child = parent.With(parent.Rules, parent.ScopeContext, RegistrySharing.CloneAndDropCache, parent.SingletonScope.Clone()))
            {
                var service2 = child.Resolve<IService>();
                Assert.AreEqual(service, service2);
            }
            Assert.IsFalse(service.IsDisposed); //child container disposed parent singleton!!!
        }
        Assert.IsTrue(service.IsDisposed);
    }

    public interface IService
    {
        bool IsDisposed { get; }
    }

    public class Service : IService, IDisposable
    {
        public void Dispose() => IsDisposed = true;
        public bool IsDisposed { get; private set; }
    }
2

There are 2 answers

0
user234878 On BEST ANSWER

If the disposing of child container is causing trouble, just don't dispose it :) Thanks Dadhi.

using (var child = parent.With(parent.Rules, parent.ScopeContext, RegistrySharing.CloneAndDropCache, parent.SingletonScope.Clone())
.OpenScope()) // Here!

There is no need to dispose child container, because by openning new scope, all the disposables will be tracked inside explicit scope.

0
Hank On

You could instead open a scoped context and it will work as expected. There are not many reasons you should need a child container that a scoped context cannot solve.

using (var child = parent.OpenScope())
{
    var service2 = child.Resolve<IService>();
    Assert.AreEqual(service, service2);
}