Vladimir
Vladimir

Reputation: 1420

Scoped Unit of Work Resolution in Prism Xamarin with DryIoc

In a Prism Xamarin app with DryIoc as container, I have a Unit of Work which is referenced by several other components which are then referenced from view models. It looks something like this (interface declarations skipped for briefness):

public class UnitOfWork : IUnitOfWork {...}

public class Service1 : IService1 {
    public Service1 (IUnitOfWork unitOfWork) {...}
}

public class Service2 : IService2 {
    public Service2 (IUnitOfWork unitOfWork) {...}
}

public class MyViewModel {
    public MyViewModel (IService1 service1, IService2 service2) {...}
}

I have registered Service1, Service2 and UnitOfWork as transient, which means that when MyViewModel is instantiated, two instances of UnitOfWork are created, one for the reference in Service1 and one for the reference in Service2. I want to have the same instance of UnitOfWork to be used for both Service1 and Service2. However, I do not want to use a singleton but instead I am looking for a scoped instantiation, with the scope being equal to the creation of the corresponding view model.

DryIoc supports scopes but I cannot find any information about using scopes in Prism. I found a site describing Prism containers and DryIoc in particular but its page about scoping is empty.

I am looking for documentation or samples how to introduce and manage scopes in Prism. Any help in these regards is appreciated.

UPDATE:

I figured out that Prism/DryIoc creates a scope for each View/ViewModel that is opened, so if the services are registered as Scoped, they will also be resolved per View/ViewModel. However, I cannot find any way to configure these scopes, assign names, etc. and also I cannot find any documentation about this.

Upvotes: 2

Views: 202

Answers (1)

Haukinger
Haukinger

Reputation: 10873

You can always, as a fallback if you like, manually create a factory for your services. Inject that into your view model together with the unit of work, and pass the unit of work to the factory when you use it to create the services.

Although it may look clunkier, I'd actually prefer that over some container-specific magic, because it's very straight forward to understand and not fragile at all.

Upvotes: 0

Related Questions