实体类:类的设计结构,在C#中
public class Customer {
public int CustomerId { get; set; }
public string Name { get; set; }
}
public class Invoice {
public int InvoiceId { get; set; }
public int CustomerId { get; set; }
public string InvoiceNo { get; set; }
}
接口:
public interface ICustomerService {
Customer GetCustomerById(int customerId);
void DeleteCustomer(int customerId);
}
public interface IInvoiceService {
Invoice GetInvoiceById(int invoiceId);
void DeleteInvoice(int invoiceId);
List<Invoice> GetAllInvoiceByCustomer(int customerId);
Customer GetInvoiceCustomer(int invoiceId);
}
类:
public class CustomerService : ICustomerService {
private readonly IInvoiceService _invoiceService = new InvoiceService();
public Customer GetCustomerById(int customerId) {
//return customer from db
return new Customer();
}
public void DeleteCustomer(int customerId) {
var invoiceList = _invoiceService.GetAllInvoiceByCustomer(customerId);
foreach (var invoice in invoiceList) {
_invoiceService.DeleteInvoice(invoice.InvoiceId);
}
//delete customer from db
}
}
public class InvoiceService : IInvoiceService {
private readonly ICustomerService _customerService = new CustomerService();
public Invoice GetInvoiceById(int invoiceId) {
//return invoice from db
return new Invoice();
}
public void DeleteInvoice(int invoiceId) {
//delete invoice from db
}
public List<Invoice> GetAllInvoiceByCustomer(int customerId) {
//get all invoice by customer id
return new List<Invoice>();
}
public Customer GetInvoiceCustomer(int invoiceId) {
Invoice invoice = GetInvoiceById(invoiceId);
return _customerService.GetCustomerById(invoice.CustomerId);
}
}
当我创造 “的CustomerService” 一个新的实例。它会返回一个错误:
An unhandled exception of type 'System.StackOverflowException' occurred
因为当我创造“的CustomerService”新实例“的CustomerService”将创造“InvoiceService”一个新的实例,“InvoiceServer”也创造了“CustomerServer”的新实例。
1)我应该将所有的方法设置为静态吗?
2)“InvoiceService”将具有来自“CustomerService”的调用方法,“CustomerService”也将调用来自“InvoiceSercie”的方法。我如何编写这些类?如果我将所有方法设置为静态,问题将得到解决,但我想这不是一个好的解决方案。
非常感谢!
+1依赖注入 –