每个 table/class asp.net webapi 一个接口

One interface per table/class asp.net webapi

我就是想问问。是否可以像这样为每个 tableclass 创建一个 interface

public interface ICustomer{
   long id;
   string firstname;
   string lastname;
}

 [Table("Customer")]
 public class Customer : ICustomer{
       public long id {get;set;}
       //implementation etc...
    }


public interface ICustomerDetails{
   long id;
   bool isMarried;
   string billingAddress;
}


[Table("CustomerDetails")]
public class CustomerDetails : ICustomerDetails{
   [Key]
   public long id {get;set;}
   //implementation etc...
}

我想应用DI原则,我现在有50张桌子。我将遵循 SOLID 原则。这是现有项目。我是 OOP 的新手,正在努力学习这个原则

在不了解你为什么要这样做的情况下,很难提供更多细节。但是,根据您在问题中提供的内容,简短的回答是否定的。您通常不会注入这些对象(实体)。

通常,您会注入服务、存储库或具有功能(方法)的东西,因为该功能在单元测试中需要有所不同(您实际上不想用例如,单元测试中的数据库)。

如果你想实例化一个客户,那就去做吧。不需要注射它。比如(这个比WebApi更MVC,但是原理是一样的):

 public class Customer
{
    public long Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public interface ICustomerRepository
{
    List<Customer> GetCustomers();
    Customer GetCustomer(long id);
    void SaveCustomer(Customer customer);
}

public class CustomerRepository : ICustomerRepository
{
    public List<Customer> GetCustomers()
    {
        // something here to retrieve the list of customers from a database 
    }

    public Customer GetCustomer(long id)
    {
        // something here to retrieve the specific customer from a database
    }

    public void SaveCustomer(Customer customer)
    {
        // save the customer
    }
}

然后您将存储库注入您的控制器:

 public class CustomerController : Controller
{
    private readonly ICustomerRepository _customerRepository;
    public CustomerController(ICustomerRepository repository)
    {
        _customerRepository = repository;
    }
    // GET: Customer
    public ActionResult Index()
    {
        var customers = _customerRepository.GetCustomers();
        // typically, here you would map the customers to a viewmodel, but for the sake of brevity...
        return View(customers);
    }

    [HttpPost]
    public ActionResult Create(FormCollection collection)
    {
        // there are better ways to do this (look at model binding), but as an example:
        var customer = new Customer();
        customer.Id = collection["id"];
        customer.FirstName = collection["firstname"];
        customer.LastName = collection["lastname"];

        _customerRepository.SaveCustomer(customer);
        return RedirectToAction("Index");
    }
}

如果这不是您想要的,也许您可​​以在您的问题中提供更多细节并更好地了解如何实现您的目标。但是如果你只是想尝试依赖注入,这就足够了。因此,不需要您创建的接口(ICustomerDetails 和 ICustomer)。

如果您不打算注入各种不同的 "tables" 或正在更改的实体或某种插件架构,那么我不知道为什么 every class 需要有一个接口。似乎出于某种未知原因,您正在为自己做额外的工作。这是你不会需要它。如果你不知道为什么需要它们,而你有 50 个,那么我会犹豫不决。

现在,如果您知道您将有不同的 CustomerDetails,无论出于何种原因,您可能需要在构造函数中的某个地方注入它们,那么就创建它,但除此之外,没有。让框架做你需要的,当它抱怨或者修复它变得非常困难时。