Injecting a Specific Instance

Nov 6, 2008 at 11:48 AM
Whilst I admit that I'm new to Prism and dependency injection, I've been using it for the last month or so and feel like I pretty much "get it". That said, there is one area that I'm a little confused over.

As an example, let's say I have a model class Person and a view model class PersonViewModel that presents the data of the Person in the PersonView, fairly standard stuff so far. However, let's move it on a bit and say that I have a PersonService that returns a specific Person model object based on a parameter to a lookup somewhere. Now I want to create a new PersonViewModel for the newly returned Person and this is where I get a bit confused.

Using standard dependency injection, I would ask the container for an instance of PersonViewModel and it would resolve all dependencies for me. If one of those dependencies is an instance of the Person model class, then it will create a new one and inject it into the PersonViewModel constructor for me, but what I want to use is the Person model instance that the PersonService returned for me. What I actually want is a way of asking the container for an instance of PersonViewModel, but use this explicit Person model instance instead.

It seems to me that I either have to register my specific Person model instance in the contained with some name that I can use to resolve it in the constructor of the PersonViewModel, which frankly smells and wouldn't behave well in a multi-threaded scenario! Or I have to resolve the PersonViewModel instance and then set a Model property on it to pass in the Person model instance. Whilst this approach is slightly better, it's reliant on the Model property being set for the PersonViewModel instance to be valid. My PersonViewModel requires a Person model instance, so I want it in the constructor that you can't get an invalid PersonViewModel.

Am I making sense? Does anyone have any suggestions for a good solution to this problem? At the moment I'm having to manually create PersonViewModel instances and manually inject the dependencies (including my Person model instance).

Many thanks,