How to create a wrapper around DryIoC container.OpenScope()?

Viewed 465

I created a wrapper around DryIoC container which is just a class that delegates tasks to DryIoC methods ( for example, myContainer.Register<T>() will call dryIoC.Register<T>() ). the goal is just to hide the real implementation behind my interface so I can switch to another DI container if I wanted to.

All works fine, but I faced a problem today when I tried to work with Scopes likes in this example code taken from here

// example using DryIoC
var container = new Container();
container.Register<B>();

using (var scope = container.OpenScope())
{
    var a = new A();
    scope.UseInstance(a); // Scoped

    scope.Resolve<B>(); // will inject `a`
}

var anotherA = new A();
container.UseInstance(anotherA); // Singleton
container.Resolve<B>(); // will inject `anotherA`

my naive wrapper implementation was to create another constructor that accepts an instance of DryIoC container and do it like this :

    // My Wrapper class
    public Infrastructure.IMyContainer OpenScope()
    {
        return new MyContainer(dryIoC.OpenScope());
    }

my understanding is that dryIoC.OpenScope() returns a new instance of the container, so all I had to do is save this instance internally and use it to resolve my classes. but that implementation didn't work for me, here my unit test :

[Test]
public void OpenScope_Creates_A_Scoped_Container()
{
    var _container = new MyContainer();
    _container.Register<IMyInterface, MyImpl>();
    _container.Register<MyDependingClass>();
    MyDependingClass cls1 = null;
    MyDependingClass cls2 = null;
    var dep = new MyImpl();
    using (var scope = _container.OpenScope())
    {
        scope.UseInstance(dep);
        cls1 = scope.Resolve<MyDependingClass>(); // this should inject 'dep' instance created in the line before the creation of the scope
    }

    cls2 = _container.Resolve<MyDependingClass>(); // this should inject another instance.

    cls1.Dep.ShouldBeSameAs(dep); // cls1 was resolved in the scope, so it should get 'dep' instance
    cls1.Dep.ShouldNotBeSameAs(cls2.Dep); // cls2.Dep should be different
}

// stub classes/interfaces
class MyDependingClass
{
    public MyDependingClass(IMyInterface dep)
    {
        Dep = dep;
    }

    public IMyInterface Dep { get; }
}

class MyImpl : IMyInterface { }

but this test fails at cls1.Dep.ShouldBeSameAs(dep); telling me that the two instances of IMyInterface was different !!! Am I missing something ??

0 Answers
Related