Malutek
Malutek

Reputation: 482

IoC container in MVVMLight - How to pass concrete implementation to the specified element?

I'm currently struggling with following problem with an IoC container from Mvvm Light - I have an interface IDataService, which is being implemented by two classes: DataService1 and DataService2. I also have MainViewModel class that has many dependencies, with one being IDataService.

The point is, I want to supply MainViewModel with DataService2, not the other one. How can I do that? I've tried to "key" both instances of the IDataService and the MainViewModel, like that:

class MainViewModel 
{
    // MainViewModel has many dependencies, 
    public MainViewModel(X x, Y y, Z z, M m, N n, IDataService dataService) { }
}

(...)

SimpleIoc.Default.Register<IDataService>(() => new DataService1(), "A");
SimpleIoc.Default.Register<IDataService>(() => new DataService2(), "B");


(...)

var viewModel = SimpleIoc.Default.GetInstance<MainViewModel>("B"); // Runtime exception

but I get runtime exception which basically says that the MainViewModel cannot be resolved - from what I've understood if I want to resolve keyed MainViewModel ("B"), all of its dependencies have to be keyed. This is not what I want - I want to resolve MainViewModel that has default dependencies, except for the one.

How can I do that? I'm clearly missing something. Thanks in advance for any help.

Upvotes: 3

Views: 619

Answers (1)

romanoza
romanoza

Reputation: 4862

Hate to say, but it looks like the only way. You have to register a keyed factory:

SimpleIoc.Default.Register<MainViewModel>(() => new MainViewModel(new X(), new Y(), new Z(), new M(), new N(), SimpleIoc.Default.GetInstance<IDataService>("B")), "B");

Upvotes: 2

Related Questions