Search code examples
c#wpfxamldependency-injectionprism

How to implement scoped services in tabs, (preferably) in a WPF application using Prism?


I'm creating a WPF application using the Prism framework and have run into an issue with dependency injection scopes. My application contains multiple tabs (2, at least for now), each with identical views and ViewModels.

It's like every tab is an instance of the software that is inside of the tab itself.

Here's the specific requirement:

  • Each tab should have its own scope (or any other way to achieve the same result).
  • Within a tab, I want to inject the same instance of a service across the multiple ViewModels in that tab.
  • The instance of the service must be different between tabs.

Note: I would like to avoid solutions that require assigning a unique ID to each tab and managing state through dictionaries like username["tab_uuid_1"]. Ideally, each ViewModel should remain unaware that it is being scoped or separated by tabs. I'm open to another solution, even if it doesn't involve using the Prism framework!


For example:

  • Tab 1 should have a unique instance of the services shared among its ViewModels.
  • Tab 2 should have a separate instance of the same services, also shared among its ViewModels.

I'm not sure how to associate a scope with a specific tab. The tabs can dynamically or statically created (it's not important!).


Solution

  • Register the services scoped as needed at your resolution root and in your main view model, create the tabs' view models in scopes.

    I'd put the creation of the view models in a service to contain the container usage as much as possible.