在ASP.NET 5控制器构造函数中注入太多的依赖项可能会影响性能和内存。为了避免这种情况,可以通过将相同类型的依赖项分组来减少注入的数量。例如,可以将所有数据访问类的依赖项分组并将它们注入到单个仓储类中。然后,可以注入这个仓储类到控制器中,而不是注入所有的数据访问依赖项。
以下是一个示例,展示了如何在ASP.NET 5控制器中分组依赖项:
public interface ICustomerRepository
{
List GetAllCustomers();
}
public class CustomerRepository : ICustomerRepository
{
private readonly MyAppDbContext _dbContext;
public CustomerRepository(MyAppDbContext dbContext)
{
_dbContext = dbContext;
}
public List GetAllCustomers()
{
return _dbContext.Customers.ToList();
}
}
public class OrderService : IOrderService
{
private readonly ICustomerRepository _customerRepository;
private readonly IOrderRepository _orderRepository;
public OrderService(ICustomerRepository customerRepository, IOrderRepository orderRepository)
{
_customerRepository = customerRepository;
_orderRepository = orderRepository;
}
public List GetOrdersByCustomerId(int customerId)
{
var customer = _customerRepository.GetCustomerById(customerId);
if (customer == null)
{
throw new ArgumentException("Invalid customer Id.");
}
return _orderRepository.GetOrdersByCustomerId(customerId);
}
}
public class HomeController : Controller
{
private readonly IOrderService _orderService;
public HomeController(IOrderService orderService)
{
_orderService = orderService;
}
public IActionResult Index()
{
var orders = _orderService.GetOrdersByCustomerId(1);
return View(orders);
}
}
在上面的示例中,数据