我们有一个需要使用DI和ASP Core的项目。 我对此非常陌生并且有一个问题。
我有一个名为HomeController的控制器,如下所示:
public class HomeController : BaseController {
private IOrderService _orderService;
public HomeController(IOrderService orderService) {
_orderService = orderService;
}
public IActionResult Index() {
var orders = _orderService.GetMyOrders();
return View(orders);
}
}
代码如下所示:
public class OrderService : BaseService, IOrderService {
public OrderService(IDataContextService dataContextService) {
_dataContextService = dataContextService;
}
public List<Orders> GetMyOrders() {
var orders = // do my code here which works fine!;
// here i need some code do check orders for delivery so
DeliveryService deliveryService = new DeliveryService(_dataContextService);
// update my orders and return these orders
return orders;
}
}
public class DeliveryService : BaseService, IDeliveryService {
public DeliveryService(IDataContextService dataContextService) {
_dataContextService = dataContextService;
}
public void MyMethod() {
}
}
public class BaseService {
protected IDataContextService _dataContextService;
}
我的几乎所有服务都有一个像OrderService和DeliveryService这样的构造函数。我的问题是,每次都必须传递_dataContextService,还是在依赖模式中有解决方案?
答案 0 :(得分:1)
你应该按照它的方式保存它,asp.net核心IoC会为你注入它,但要确保它是按照请求注入的,这将有助于为每个请求只为一个上下文进行身份验证并在请求后处理它服务。
您可以在ConfigureServices
课程的Startup
课程中注册上下文和服务,如下所示
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
// Add application services.
services.AddTransient<HomeController>();
services.AddTransient<IOrderService , OrderService >();
services.AddTransient<IDeliveryService, DeliveryService>();
services.AddScoped<IDataContextService , YourDataContextService >();
}
AddScoped
方法将为每个HTTP请求创建一个对象实例