且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在静态方法中使用依赖注入?

更新时间:2023-10-09 21:02:04

如果您必须保留静态方法,我会将静态调用包装在存储库中

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.)