c# - How should I communicate between layers and optimize my code? -


i'm building rest web api on c#. code divide in 4 layers:

  • model
  • repository
  • service
  • web api

how can connect service , repository model efficient, without repeat lote of code? right 1 of service layer class looks 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 me inneficient, , find myself writting lots of identical classes? ideas? thanks

there no simple or short/quick answer question. also, lot of variables comes play when designing systems architecture. give few generic advices:

  • make decisions late possible, more knowledge have before making decision better;
  • prototype, try out concepts in smaller scale;

for particular code sample common practise isolate code in single place (service) while injecting action , using command follow dry. also, 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;     pubic 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);             }         }     } } 

Comments

Popular posts from this blog

neo4j - finding mutual friends in a cypher statement starting with three or more persons -

php - How to remove letter in front of the word laravel -

minify - Minimizing css files -