开发者

pass parameter to IServiceLocator

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 开发者_StackOverflow社区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 (Customer in 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 a ICustomerRepository service. You can register an ICustomerRepository implementation 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.


If you write a wrapper for the ServiceLocator you can hold the unity container within the wrapper and the expose an additional resolve method overload that takes the ParameterOverrides property. Then the method could use the unity container to do the resolution as per your first code snippet rather than the ServiceLocator code snippet.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜