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

Asked

Viewed 67 times

2

I have my class Service calling for GrupoService, in it are most of the shares that refer to a Grupo.

Crud(Inserir,Alterar,Excluir,Listar)

The only dependency I have in my class so far is the GrupoRepository. Also got into 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 the Item in my class GrupoService?

Injecting the ItemRepository along with GrupoRepository, or I put ItemService?

  • 1

    If you are working with the Entity Framework, the best way is to put it in model.Itens, because the Entity Framework solves this at the consistency level. By separating too much you are creating a complicator and subusing the tool.

1 answer

3

The ideal is that all "Repository" your receive in the constructor an instance of Database Context (In the case of Entityframework, Dbcontext) there you will always have the same scope of database, transaction and connection.

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

Sort of 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 adapting this example to any Ioc you are using.

  • I agree with everything in that reply, but what about grupo.Itens, which is the focus of the question?

  • I put more details of the idea, can be improved, but no time now

  • it is much better to be using a Repository Base, using Generic

Browser other questions tagged

You are not signed in. Login or sign up in order to post.