Search code examples
c#n-tier-architecture

How should I communicate between layers and optimize my code?


I'm building a REST Web API on C#. My code is divide in 4 layers:

  • Model
  • Repository
  • Service
  • Web API

How can I connect Service and Repository model efficient, without repeat a lote of code? Right now one of my Service Layer class looks like this:

public class ContactosService : IContactosService
{
    public string EmpresaId { get; set; }

    public void AddContact(Contact_mdl value)
    {
        using (var myCon = new AdoNetContext(new AppConfigConnectionFactory(EmpresaId)))
        {
            using (var rep = new Contact_rep(myCon))
            {
                rep.Add(value);
            }
        }
    }

    public void DeleteContact(int id)
    {
        using (var myCon = new AdoNetContext(new AppConfigConnectionFactory(EmpresaId)))
        {
            using (var rep = new Contact_rep(myCon))
            {
                rep.Delete(id);
            }
        }
    }
}

This looks to me to be very inneficient, and I find myself writting lots of almost identical classes? Any ideas? thanks


Solution

  • There is no simple or short/quick answer to your question. Also, a lot of variables comes into play when designing systems architecture. I would just give a few generic advices:

    • Make your decisions as late as possible, the more knowledge you have before making decision the better
    • Prototype, try out concepts in a smaller scale

    For you particular code sample, it would be common practise to isolate code in a single place (service) while injecting action and using it as a command to follow DRY. Also, it avoids inconstencies while refactoring.

    Consider example:

    public class ContactosService : IContactosService
    {
        private readonly IContactRepository repository;
    
        public ContactosService(IContactRepository repository)
        {
            this.repository = repository;
        }
    
        public void AddContact(Contact_mdl value)
        {
            repository.Execute(rep => rep.Add(value));
        }
    
        public void DeleteContact(int id)
        {
            repository.Execute(rep => rep.Delete(id));
        }
    }
    
    public class ContactRepository : IContactRepository
    {
        private readonly string _empresaId;
        public ContactRepository(string empresaId)
        {
             _empresaId = empresaId;
        }
    
        public void Execute(Action<Contact_rep> command)
        {
            using (var myCon = new AdoNetContext(new AppConfigConnectionFactory(_empresaId)))
            {
                using (var rep = new Contact_rep(myCon))
                {
                    command(rep);
                }
            }
        }
    }