在ASP.Net Core中使用策略模式的解决方法如下:
public interface IShippingStrategy
{
decimal CalculateShippingCost(decimal orderTotal);
}
public class StandardShippingStrategy : IShippingStrategy
{
public decimal CalculateShippingCost(decimal orderTotal)
{
return orderTotal * 0.05m;
}
}
public class ExpressShippingStrategy : IShippingStrategy
{
public decimal CalculateShippingCost(decimal orderTotal)
{
return orderTotal * 0.1m;
}
}
services.AddScoped();
services.AddScoped();
public class OrderService
{
private readonly IShippingStrategy _shippingStrategy;
public OrderService(IShippingStrategy shippingStrategy)
{
_shippingStrategy = shippingStrategy;
}
public decimal CalculateShippingCost(decimal orderTotal)
{
return _shippingStrategy.CalculateShippingCost(orderTotal);
}
}
这样,当需要使用不同的配送策略时,只需要通过构造函数来注入不同的具体策略类即可。
注意:上述代码是ASP.Net Core中使用DI和策略模式的基本实现方法,具体的使用场景和业务逻辑可能会有所不同,需要根据实际情况进行调整。