1

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.

Haukinger
  • 10,420
  • 2
  • 15
  • 28
  • Can you update your question and express why you need this and why the usual `Scoped` lifestyle wouldn't work for you? – Steven Apr 20 '22 at 13:24
  • 1
    I want an implicit scope without having to manually open one. `PerResolveLifetimeManager` provides an automatic unit-of-work (per view model). – Haukinger Apr 20 '22 at 13:30

1 Answers1

2

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 ) );
dadhi
  • 4,807
  • 19
  • 25
  • Actually, I've stumbled across `Reuse.ScopedTo<>` and I thought was meant to scope to a _concrete_ type, here `A`. I need to scope to _any_ view model that's resolved. Does `ScopedTo` automatically scope to all types derived from `BaseType`, for example? – Haukinger Apr 20 '22 at 14:07
  • 1
    @haukinger Here is the exempt from the doc: *You may match not only the exact TService but its base class or the implemented interface.* – dadhi Apr 20 '22 at 18:58