SimonAx
SimonAx

Reputation: 1378

Passing runtime arguments to constructor using SimpleIoc

Currenlty I'm using SimpleIoC from MvvmLight and I cannot figure out how to supply the constructor parameters to a class that implements IMyService. I've found the following SO thread MVVM SimpleIoc, how to use an interface when the interface implementation requires construction parameters , and it suggests that I simply need to pass the constructor argument when registring the implemententation to the interface, e.g.

SimpleIoc.Default.Register<IMyService>(() => {
  return new MyServiceImplementation("Hello World");
});

However, this registration is located in the ViewModelLocator class, which has now knowledge on the actual constructor parameter. Instead of being "Hello world", it could be "Hi there" but that is not know at compile time. Is there any way to pass the constructor arguments at runtime?

Currently I only see two options: (1) register IMyService in the viewmodel, or (2) remove the constructor parameter altogether and provide a property that needs to be set. Neither option seems right, so I'd very much appreciate any suggestions on how to pass constructor arguments to MyServiceImplementation.

Upvotes: 0

Views: 2508

Answers (1)

SimonAx
SimonAx

Reputation: 1378

From the SO question SimpleIoc - can it provide new instance each time required? I gathered that SimpleIoc from MvvmLight acts like a repository of singleton viewmodels. It therefore doesn't maky any sense to provide constructor paramerters to an instance implementing IMyService except for in the ViewModelLocator.

For now, I've removed the constructor parameters (option 2 in my original question), but in the future I may switch to a different library such as Ninject.

Upvotes: 1

Related Questions