C# 具有初始参数的类是否可以使用控制模式反转(IoC)?

C# 具有初始参数的类是否可以使用控制模式反转(IoC)?,c#,asp.net-mvc,asp.net-core,inversion-of-control,ioc-container,C#,Asp.net Mvc,Asp.net Core,Inversion Of Control,Ioc Container,我很好奇,初始参数为的类是否可以使用控制模式反转(IoC) 例如: 带有搜索按钮的页面可以通过类帮助器实例化来搜索订单详细信息 类别: public类OrderDetail { 订单; public OrderDetail(字符串orderID) { order=DumbOrderList()。其中(o=>o.orderID==orderID); } 公共价格() { 重新运行订单。价格; } public datetime GetDate() { 重新运行订单。日期; } ... ... ..

我很好奇,初始参数为的类是否可以使用控制模式反转(IoC)

例如:

带有搜索按钮的页面可以通过类帮助器实例化来搜索订单详细信息

类别:

public类OrderDetail
{
订单;
public OrderDetail(字符串orderID)
{
order=DumbOrderList()。其中(o=>o.orderID==orderID);
}
公共价格()
{
重新运行订单。价格;
}
public datetime GetDate()
{
重新运行订单。日期;
}
...
...
...
}
第页:

[HttpPost]
公共IActionResult搜索(字符串orderID)
{
OrderDetail orderHelper=新的OrderDetail(orderID);
返回Json(orderHelper.GetPrice());
}
页面依赖于
OrderDetail
类,每次搜索都将使用
orderID
实例化类

如何使用IoC模式制作
OrderDetail


或者如果它不能使用IoC模式,那么我如何才能使页面不依赖于此类(解耦)?

实际上,您设计类的方式可以改进。不要使类依赖于某个要实例化的参数,而是使该类的方法依赖于该参数

我的意思是,重新设计OrderDetail类,如下所示:

1.)创建一个接口

public interface IOrderDetail 
{
    GetPrice(int orderId)
}
public class OrderDetail : IOrderDetail
{
    public GetPrice(int orderId) {....}
}
2.)创建一个实现接口的类

public interface IOrderDetail 
{
    GetPrice(int orderId)
}
public class OrderDetail : IOrderDetail
{
    public GetPrice(int orderId) {....}
}
3.)在IoC容器中注册依赖项

container.RegisterType<IOrderDetail, OrderDetail>();

对于控制模式的反转,您需要定义一个接口,
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());
}