How to simulate Unity's PerResolveLifetimeManager
with DryIoc?
That is, reuse within the current call to resolve, but not otherwise:
var a = container.Resolve<A>();
Assert( ReferenceEquals(a.B.D, a.C.D ) );
var a2 = container.Resolve<A>();
Assert( !ReferenceEquals(a.B.D, a2.B.D ) );
with
class A
{
public B B {get;}
public C C {get;}
}
class B
{
public D D {get;}
}
class C
{
public D D {get;}
}
With Unity, I'd register D
with a PerResolveLifetimeManager
, but I've got no idea how to achieve that with DryIoc.
In my application, A
might be a top-level view model and D
an Entity Framework context: whenever I navigate (i.e. resolve a new view model), I want to create a new context to be used while this view model is active, and I want it to be shared by all dependencies that view model might have.
Here is the doc and the example below:
container.Register<A>(setup: Setup.With(openResolutionScope: true));
container.Register<B>(Reuse.ScopedTo<A>());
container.Register<D>(Reuse.ScopedTo<A>());
var a = container.Resolve<A>();
Assert( ReferenceEquals(a.B.D, a.C.D ) );
var a2 = container.Resolve<A>();
Assert( !ReferenceEquals(a.B.D, a2.B.D ) );