Search code examples
wpfinversion-of-controlioc-containersimple-injector

How to solve the Simple Injector error "the instance is requested outside the context of an active (Async Scoped) scope" in WPF with MVVM?


I have application written in WPF and MVVM and I've used Simple Injector as IoC Container. My main view model has constructor in that I inject bll class:

public MainWindowViewModel(IReviewBodyBLL reviewBodyBLL)
{
    this.reviewBodyBLL = reviewBodyBLL;

and this view model is setup in MainWindow:

public partial class MainWindow : Window
{
    public MainWindow(MainWindowViewModel viewModel)
    {
        InitializeComponent();

        base.DataContext = viewModel;

and all classes are registered:

container.Register<IFreewayReviewCreatorDbContext, FreewayReviewCreatorDbContext>(Lifestyle.Scoped);
container.Register<IUnitOfWorkFactory, UnitOfWorkFactory>(Lifestyle.Scoped);
container.Register<IUnitOfWork, UnitOfWork>(Lifestyle.Scoped);
container.Register<IReviewBodyBLL, ReviewBodyBLL>(Lifestyle.Transient);

// Register your windows and view models:
container.Register<MainWindow>();
container.Register<MainWindowViewModel>();

and I get error when I try to run application:

Exception thrown: 'SimpleInjector.ActivationException' in SimpleInjector.dll

The program '[28028] FreewayReviewCreator.exe' has exited with code 0 (0x0).

Application stop without any break.

When I remove from main view model constructor IReviewBodyBLL reviewBodyBLL application start correctly. How to inject bll to the constructor?


Solution

  • For a WPF application, where you can have multiple windows open at the same time, where each window should run in its own scope, Simple Injector's ambient scoping model will not work, because it becomes unclear when to dispose a single scope, as there will typically always be a window open.

    Instead, you can use Simple Injector's "flowing" scoping model, as described in this Q/A about Win Forms. This will work the same for WPF.