简体   繁体   中英

How Should viewmodels communicate with repositories?

I got a bunch of repositoiries. They retrive data from a EF 3.5 generated model. For the sake of simplicity let's just call them repository1,2 and 3. They all implement the generic interface: public interface IRepository<T>{..} How should my viewmodels communicate with theese repositories? I tried to create some kind of a factory with a IRepository GetRepository(string repositoryName){..} method, but I couldn't get it to work. So should I just reference the repositories in the viewmodels when needed or is there a better solution to this? I would prefer a code sample, thanks.

cheers

These answers and the free introduction-chapter from Dependency Injection in .NET recommend having the repositories and ui separated from the businesslogic. Dependencies should go towareds the core-logic like this:

dal/repositories -> Businesslayer, Models and IRepository <- UI

I have also wondered where the ViewModels fit into this. They should definetly not be connected to the repositories at all, but whether the ViewModels belong in the businesslayer (servicelayer) or with the UI seems debatable. I'm just staring out with asp.net mvc and are currently most if favour of putting them with the businesslayer to keep the controllers simple. Also it seems reasonable that the businesslayer gathers items from various repositories that logically belong together and that they are acted on together via the ViewModel. Maybe as a transaction, so that updates to all repositories must succeed or be rolled back.

I can't think of a situation where your view model should EVER communicate with your repository. A ViewModel should be a flat model for use by the Client.

What exactly are you trying to do?

You might find the BookLibrary sample application of the WPF Application Framework (WAF) interesting. It uses the Entity Framework together with MVVM. But it doesn't introduce a repository to work with the Entity Framework.

A Repository serves up T's. What I've done is add a static property to my T's to get the repostory via IOC:

public class Part // This is one kind of T
{
    public static IRepository<Part> Repository { get { return IoC.GetInstance<IRepository<Part>>(); } }
    ...
}

then when I need a Part...

var part = Part.Repository.Find(id);

For my unit testing IoC serves up mock repositories. In production, the real thing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM