I have a ViewModel class which I want to resolve via the unity ServiceLocator, but my viewModel requires a parameter to the constructor. The parameter’s type is one of the entities in my application (a Customer object) rather than some service implementation. I know that coding against the Unitycontainer itself I can pass a paramater like this:
_container.Resolve<CustomerDetailViewModel>(new ParameterOverrides {{"customer", customer}});
but if I dont have direct access to the container I need to go via the ServiceLocator like this:
(CustomerDetailViewModel)ServiceLocator.Current.GetInstance<CustomerDetailViewModel>();
However using the second approach I have no way to pass in any parameters to the ServiceLocator. Is there any way this can be done? Is it “wrong” to get an instance of the Container from the ServiceLocator and then use that?
The problem is that you are trying to inject an entity (
Customerin this case) into a class. Entities are short lived objects and they don’t tend to be good candidates for being injected.Instead of injecting a
Customer, inject aICustomerRepositoryservice. You can register anICustomerRepositoryimplementation in the startup path of the application and this way you won’t have to call the container directly, which makes the application design cleaner and the unit tests easier.