我很好奇,具有初始参数的类可以使用控制反转模式(IoC)吗?
示例:
带有搜索按钮的页面可以通过Class助手实例化来搜索订单详细信息。
class:
public class OrderDetail
{
order order ;
public OrderDetail(string orderID)
{
order = DumbOrderList().where(o=>o.orderID == OrderID);
}
public decimal GetPrice()
{
retrun order.Price;
}
public datetime GetDate()
{
retrun order.Date;
}
...
...
...
}
页:
[HttpPost]
public IActionResult Search(string orderID)
{
OrderDetail orderHelper = new OrderDetail(orderID);
return Json(orderHelper.GetPrice());
}
页面取决于OrderDetail
类,每次搜索都将使用orderID
实例化类。
如何使用IoC模式制作OrderDetail
类?
或者如果它不能使用IoC模式,那么如何使页面不依赖于此类(解耦)?
实际上,您设计课堂的方式可以得到改善。不必使类依赖于要实例化的某些参数,而应使该类的方法依赖。
我的意思是说,重新设计OrderDetail类,如下所示:
1。)创建接口
public interface IOrderDetail
{
GetPrice(int orderId)
}
2。)创建一个实现接口的类
public class OrderDetail : IOrderDetail
{
public GetPrice(int orderId) {....}
}
3。)在IoC容器中注册依赖项
container.RegisterType<IOrderDetail, OrderDetail>();
4。)像下面在API Controller中一样使用它
public class SomeController : ApiController
{
private readonly IOrderDetail _orderDetail;
public SomeController(IOrderDetail orderDetail)
{
_orderDetail = orderDetail;
}
[HttpPost]
public IActionResult Search(string orderID)
{
return Json(_orderDetail.GetPrice(orderID));
}
}
通过反转控制模式,您需要定义一个接口,Search
可以将其委派给该接口。接口定义可能是主观的,因此这里没有一个答案。
如果我是根据有关示例执行控制反转的人,我会这样做:
interface IOrderPriceGetter
{
decimal GetByOrderId(int orderId);
}
class OrderPriceGetter : IOrderPriceGetter
{
public decimal GetByOrderId(int orderId)
{
return new OrderDetail(orderId).GetPrice();
}
}
[HttpPost]
public IActionResult Search(string orderID)
{
// Injected via constructor
IOrderPriceGetter getter = ...;
return Json(getter.GetByOrderId(orderId));
}
或者我也可以将接口定义为:
interface IOrderGetter
{
OrderDetail GetOrder(int orderId);
}
然后像这样使用它:
[HttpPost]
public IActionResult Search(string orderID)
{
// Injected via constructor
IOrderGetter getter = ...;
return Json(getter.GetOrder(orderId).GetPrice());
}