我应该如何在层之间进行通信并优化我的代码?

How should I communicate between layers and optimize my code?

我正在 C# 上构建 REST Web API。我的代码分为 4 层:

  • Model
  • Repository
  • Service
  • Web API

如何在不重复大量代码的情况下有效地连接服务和存储库模型?现在我的服务层之一 class 看起来像这样:

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

这在我看来非常无能,而且我发现自己写了很多几乎相同的 classes?有任何想法吗?谢谢

您的问题没有简单或 short/quick 的答案。此外,在设计系统架构时,很多变量都会发挥作用。我只想给出一些通用的建议:

  • 越晚做决定,做决定前了解的越多越好
  • 原型,在较小的范围内尝试概念

对于您的特定代码示例,通常的做法是将代码隔离在一个地方(服务),同时注入操作并将其用作遵循 DRY 的命令。此外,它避免了重构时的不一致。

考虑示例:

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