开发者

MVVM C# Question

I am currently learning MVVM abd the tutorial I have been using, simply uses a single View Model with a single Model. The View Model is injected with the Model interface as such:

开发者_如何学JAVA
public ViewModel(IQuoteSource quoteSource)
{

}

This is handled via DI using Unity. My question is what if the VM is dependent on multiple Models, say an arbitrary 6 or 7? Do we simply inject each of them into the ctor or should there be seperate VM's for this?

Or should each model try to implement a specific interface that exposes a couple of methods/events such as register to hook into and then an event once the data has been updated?

Thanks.


That is a lot of models for your VM to depend on. You can inject all those on the constructor, this makes the dependence more explicit and visible. Or you can have the VM resolve the various models from the Unity container:

public ViewModel(IUnityContainer container) 
{
    IQuoteSource model1 = container.Resolve<IQuoteSource>();
    ... etc ...
}

When a concrete instance is resolved using Unity and you have not specified any constructor parameters in the Resolve() call, Unity will examine the constructors from most complicated to most basic, if it finds one that takes a Unity container then it will use it (it will potentially use others first if it finds them).1 So if your VM takes a Unity container in the constructor, it can then use that container to further resolve anything it needs.

Some may argue over which method is more suitable - direct injection of all required dependencies, or injecting just the container that has the dependencies. IMVHO there are positives and negatives to both approaches, use whichever suits your style better.

You could also consider refactoring your code somewhat, maybe introduce a new Model that is a facade over several existing models. The other possibility is what you have termed a Model may actually be more suitable as a service (a tell-tale sign of this is if the model is used in several places to fetch data from a specific source, if this is the case then you can separate out that functionality into a service and cart that around in the Unity container for it to be consumed as necessary).



1 Reference: Telling Unity Which Constructor to Use when Initializing a Class

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜