如何在静态方法中使用依赖注入? [英] How to use Dependency Injection with Static Methods?
问题描述
想象一下,有一个 Customer
类,它带有一个实例 Load()
方法。
Imagine there is a Customer
class with an instance Load()
method.
调用 Load()
方法时,它将通过以下方式检索订单详细信息:
When the Load()
method is called, it retrieves order details by e.g.
var orders = Order.GetAll(customerId, ...);
GetAll()
是 Order
类和输入参数是在 Customer
类中定义的字段。
GetAll()
is a static method of the Order
class and the input parameters are fields defined in the Customer
class.
如您所见, Order
是 Customer
类的依赖项,但是,我可以不仅要创建 IOrder
并将其注入那里,因为接口不能具有静态方法。
As you can see, Order
is a dependency of the Customer
class, however, I can't just create an IOrder
and inject it there as interfaces can't have static methods.
因此,问题是如何在此示例中引入依赖注入?
Therefore, the question is how could I introduce dependency injection in this example?
我不想创建 GetAll()
实例方法,因为它是静态方法,需要保持这种状态。
I don't want to make GetAll()
an instance method since it's a static method and need to keep it that way.
例如,我在设计中使用了实用工具类,其中大多数只包含静态方法
For example, I have used utility classes in my design, most of which just contain static methods.
推荐答案
如果您必须保留静态方法,我会将静态调用包装在存储库中
If you must keep the static method, I would wrap the static calls in a Repository object.
就像这样:
interface IOrderRepository {
IEnumerable<IOrder> GetAll(customerId, ..);
}
class OrderRepository : IOrderRepository {
IEnumerable<IOrder> GetAll(customerId, ...)
{
Order.GetAll(customerId,...); // The original static call.
}
}
现在您将此存储库注入到 Customer
类。
Now you inject this repository into your Customer
class.
(我假设您正在这样做,因此可以在运行时注入伪造的IOrder进行测试。应该说总体上来说,静态方法是测试的严重障碍。)
(I'm assuming you're doing this so you can inject fake IOrders at runtime for testing purposes. I should say that in general, static methods are a serious obstacle to testing.)
这篇关于如何在静态方法中使用依赖注入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!