How to work with more than one dependency in Service class?

2

I have my class Service called GrupoService , in it are most actions that refer to Grupo .

Crud(Inserir,Alterar,Excluir,Listar)

The only dependency I have on my class so far is GrupoRepository . You also have in it methods to insert, change, delete, delete.

So basically I do

public Grupo Inserir(Grupo model)
{
   return grupoRepository.Inserir(model);
}

But my group contains Itens , what is the correct way to inject Item into my GrupoService class?

Injecting ItemRepository along with GrupoRepository , or I put ItemService ?

    
asked by anonymous 16.09.2014 / 22:58

1 answer

3

Ideally, your Repository receives in the constructor an instance of the Database Context (In the case of EntityFramework, DbContext) there you will always have the same scope of transaction, transaction, and connection.

And I would use the same Group Repository to save the items, because in your "business" you can not save an item only without the group, do you agree?

More or less like this:

public class GrupoService
{
    IGrupoRepository _repository;
    public GrupoService(IGrupoRepository repository)
    {
         this._reposytory = reposiotory;

    }
    public Grupo Inserir(Grupo model)
    {
        return grupoRepository.Inserir(model);

        foreach(var item in model.Items)
        {
             grupoRepository.InserirItem(item);
        }
    }
}
public class GrupoRepository: IGrupoRepository 
{
    DbContext _db;
    public GrupoRepository(DbContext db)
    {
        this._db = db;
    }

    public Item InserirItem(Item model)
    {
        this._db.Items.Add(model);
        this._db.SaveChanges();
    }
}


//Usando
GrupoService gs = new GrupoService(new GrupoRepository( new MyDbContext("connString")));

You can try to adapt this example to some IoC that you are using.

    
16.09.2014 / 23:32