moortuvivens
moortuvivens

Reputation: 63

How do apply I Dependency Injection with MvvM?

I've read Mark Seemann's book Dependency Injection in .NET. And I think I understand most of what he wrote.

The problem that I'm struggeling with is that I want to inject viewmodels into views. I know this can be done by

public class CompositeRoot
{
    private IContainer container;
    public CompositeRoot()
    {
        //build the container
        var builder = new ContainerBuilder();
        builder.RegisterType<DatabaseContext>().As<IDatabaseContext>();
        builder.RegisterType<MainViewModel>().As<IMainViewModel>();
        container = builder.Build();

        //create a window and inject a viewmodel
        MainWindow mainWindow = container.Resolve<MainWindow>();
        mainWindow.DataContext = container.Resolve<IMainViewModel>();
        mainWindow.Show();
    }
}

but this seems rather crude.

I was thinking about:

public class CompositeRoot
{
    private IContainer container;
    public CompositeRoot()
    {
        //build the container
        var builder = new ContainerBuilder();
        builder.RegisterType<DatabaseContext>().As<IDatabaseContext>();
        builder.RegisterType<MainViewModel>().As<IMainViewModel>();
        container = builder.Build();

    }

    public IMainViewModel MainVM
    {
         get { return container.resolve<IMainViewModel>(); }
    }
}

And then put in the xaml code

DataContext="{Binding MainVM, Source={StaticResource IoC}}"

(in the app.xaml I would have compositeroot be named a resource as IoC)

My question now is, would this be good Dependency Injection, or would this still be the Service locator pattern (which is an anti pattern so I don't want to use it)

if this is the anti pattern, what are my options?

Upvotes: 4

Views: 330

Answers (1)

Matt Cole
Matt Cole

Reputation: 2601

Your solution looks perfectly valid to me. In fact this is the same approach that is used in the MVVM light library (CompositionRoot is named ViewModelLocator instead). The important point is that the locator is just for use when binding views to view models, and should not be injected into view models (this would be the service locator pattern you are trying to avoid).

Upvotes: 1

Related Questions