Erik Schierboom
Erik Schierboom

Reputation: 16646

How to use Autofac to inject ViewModels in a Windows Phone 8 application?

I want to be able to inject ViewModels into the Views in my Windows Phone 8 application using Autofac as my IoC container. How do I go about doing this? I have looked at the Caliburn.Micro framework, but I'd like to use something simpler.

Upvotes: 3

Views: 3484

Answers (1)

Erik Schierboom
Erik Schierboom

Reputation: 16646

Precisely for this purpose I have created a small demo application. It defines a ViewModelLocator class:

public class ViewModelLocator
{
    private readonly IContainer container;

    public ViewModelLocator()
    {
        var containerBuilder = new ContainerBuilder();
        containerBuilder.RegisterType<MainViewModel>();
        containerBuilder.RegisterType<ItemViewModel>();

        this.container = containerBuilder.Build();
    }

    public MainViewModel MainViewModel
    {
        get
        {
            return this.container.Resolve<MainViewModel>();
        }
    }

    public ItemViewModel ItemViewModel
    {
        get
        {
            return this.container.Resolve<ItemViewModel>();
        }
    }
}

To use this class from your views, you have to add it to your application's resources. You do this by modifying the Application.Resources section in App.xaml:

<Application.Resources>
    <local:ViewModelLocator xmlns:local="clr-namespace:AutofacWP8DependencyInjectionDemo" x:Key="ViewModelLocator"/>
</Application.Resources>

Now you will be able to inject the view model in the view. Just have the view point to the DataContext. To reference the MainViewModel as the DataContext simply add the following to your view:

DataContext="{Binding Path=MainViewModel, Source={StaticResource ViewModelLocator}}"

You can see that it sets the DataContext to the MainViewModel property of the ViewModelLocator class, which uses Autofac to create the MainViewModel instance using dependency injection.

You can find the source here: https://github.com/ErikSchierboom/autofacwp8dependencyinjectiondemo.git

Upvotes: 4

Related Questions