开发者

Do I call my Services from the ViewModel OR Model in MVVM design pattern?

开发者 https://www.devze.com 2023-01-27 09:20 出处:网络
I was asking another question here on SO and one user really confuse开发者_开发百科d me suggesting to make the following: I have read it a 1000 times on SO, that an entity should never make a save/add

I was asking another question here on SO and one user really confuse开发者_开发百科d me suggesting to make the following: I have read it a 1000 times on SO, that an entity should never make a save/add/delete call via a service to the database. Thats the task of the ViewModel!

What do you say?

public class School
{
   private ISchoolRepository _repository;

   public string Name { get; set; }

   public School()
   {
      this._repository = IoC.Resolve<ISchoolRepository>();
   }

   public bool IsValid()
   {
     // Some kind of business logic?
     if (this.Name != null)
     {
       return true;
     }

      return false;
   }

   public void Save()
   {
      if (this.isValid())
      {
         this._repository.Save(this)
      }
}


I would not mix the repository with the entities either because I like the entities to be free of any contextual or environmental state. I think managing the storage of the entities is the sole responsibility of the repository.

What would happen if you have dependencies between entities? For example, a school has students. You can’t save students until you save the school. You would have to build this logic into your student entities. Would your students save the school also? Would they refuse to save? Do they need to check the database for the school? They will at least need to know something about the school so you then create a dependency between school and students that is pretty hard wired.

Then you add teachers and you need to add similar logic for them. Your code to represent these relationships and dependencies is then spread across many entities. Think about transactions too. Then add in multiple tiers. Do you see how complicated this could become? Pretty soon you have spaghetti with meatballs and cheese!

It's the repositories’ responsibility to know this stuff.

HTH

Cheers


Calling the service from your entity violates the Single Responsibility Principle. If, in the future, you need to have your entities hydrated from a different backing store than the service you will have to change all your entities. Even though you are injecting the repository it is still violating SRP.


I dont understand what is wrong with this approach, if I wanted to swap out from say SQL server to Oracle I would simply register a new repository called "OracleSchoolRepository and it ensure it satisfies the ISchoolRepository interface.

I dont see any issues with that? Can you highlight a scenario when the above would become a problem?

Thanks!

Ben

0

精彩评论

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