ViewModel instance creation

May 15, 2012 at 3:45 PM


when I will let some dependencies be injected to a viewmodel,
Catel tells me that no empty constructor can be found.

After digging a bit within ConstructViewModelUsingArgumentOrDefaultConstructor I found it is not designed to do dependency injection at all, or did I miss something here?

Anyway, how do you think about the following idea:
When the service locator knows about an implementation of the following interface, it will use this one to create ViewModel instances.
This implementation could use an external DI container to create the needed instances.
When it returns no instance, fall back to the usual construction logic.

Please keep in mind, I had no intense look about this.
Probably there is existing another way to do this right now.

regards, Alexander.

        public interface IViewModelFactory
            IViewModel CreateInstanceOf(Type viewModelType, object withInjectionObject);

May 15, 2012 at 6:54 PM
Edited May 15, 2012 at 6:54 PM

I've just seen that the DetermineViewModelInstance event described here may do this job.
Will check this tomorrow... 

May 16, 2012 at 5:33 AM

Hmm, I think the DetermineViewModelInstance is not what I am looking for.
I would like to have a global hook which is called by Catel every time a ViewModel instance has to be created.
It seems both existing techniques have to be called within the view itself.
But I do not want to let the View do the VM instancing job at all.

Maybe a global Catel event raised on every VM instancing could do this job, or the interface solution from the first post.
Or still I am missing something here :-)

best regards,

May 16, 2012 at 7:53 AM

I don't want to abuse the servicelocator for this because it should be used without MVVM at all. However, I think it is a really good idea to create a IViewModelFactory which allows more customization.

The only thing I have to think about is how the DetermineViewModelType and DetermineViewModelInstance will go hand in hand. For example, I think that the Factory should be the default, but the views can override its behavior using the Determine methods. This way, we don't break anything but implement a great new list of possibilities :)


May 16, 2012 at 10:33 PM

Done, only unit tests left, but you can test it yourself already :)