Search code examples
c#wpfmvvmtypesdatacontext

How to Resolve View Model with Autofac having just Type of the view model?


In application with Autofac container and having registered VM I need to assign DataContext in a situation, where i have just view models Type.

MainViewModel calls NavigationService:

await NavigationService.NavigateToAsync<UpdateViewModel>();

And in my service class, how to do from this (this works fine):

private async Task InternalNavigateToAsync(Type viewModelType, object parameter)
        {
            var bootStrapper = new BootStrapper();
            var container = bootStrapper.BootStrap();

            Window window = CreateWindow(viewModelType, parameter);
            //this works fine
            if (viewModelType.Name == "MainViewModel")
            {
                window.DataContext = container.Resolve<MainViewModel>();
            }
            if (viewModelType.Name == "UpdateViewModel")
            {
                window.DataContext = container.Resolve<UpdateViewModel>();
            }
            window.Show();
        }

this (is not working):

private async Task InternalNavigateToAsync(Type viewModelType, object parameter)
        {
            var bootStrapper = new BootStrapper();
            var container = bootStrapper.BootStrap();

            Window window = CreateWindow(viewModelType, parameter);
            //but how to do this?
            window.DataContext = container.Resolve<viewModelType>();

            window.Show();
        }

And it gives me an error:

'viewModelType' is a variable but is used like a type


Solution

  • Pass the type as argument to Resolve(Type serviceType)

    window.DataContext = container.Resolve(viewModelType);
    

    instead of trying to use it as a generic argument