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
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:
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);
}
}
}
}