How to avoid an anemic domain and avoid placing your data access class inside your domain class?

I am trying to get my business logic out of my service class and my controller and put it in my business class.

public interface IFoo{
  IBar CreateBar(creationParameters);
}
public class FirstFoo : IFoo{
  IBar CreateBar(creationParameters){
    return new FirstBar(creationParameter.Id);
  }
}
public interface IBar{
  void DoSomething();
}
public class FirstBar : IBar{
  FirstBar(int id){...}
  void DoSomething(){
    //well... do something
  }
}
public class SecondBar : IBar{
  FirstBar(int id){...}
  void DoSomething(){
    //well... do something else
  }
}

Suppose I need to create a SecondFoo that will need access to the database in order to know that it needs to create a FirstBar or SecondBar, how do I do this? Am I inserting my data source into the SecondFoo constructor? Service locator? Am I moving createBar from IFoo?

EDIT: I'm not looking for a Factory template definition, the createBar method can be something like "changeBar" or "doBusinessWithBar".

+3
source share
1 answer

, SecondFoo, , , FirstBar SecondBar

, SecondFoo - , , FirstBar SecondBar. , . .

IBar CreateBar(creationParameters) {
  if (strategy.ShouldCreateFirst(creationParameters)) {
    return new FirstBar(creationParameter.Id);     
  }  
  else {
    return new SecondBar(creationParameter.Id);     
  }
}
+2

All Articles