How to use Dependency Injection with Static Methods?

后端 未结 3 1842
旧巷少年郎
旧巷少年郎 2020-12-14 21:10

Imagine there is a Customer class with an instance Load() method.

When the Load() method is called, it retrieves order details

3条回答
  •  别那么骄傲
    2020-12-14 21:31

    If you must keep the static method, I would wrap the static calls in a Repository object.

    Like this:

    interface IOrderRepository {
       IEnumerable GetAll(customerId, ..);
    }
    
    class OrderRepository : IOrderRepository {
       IEnumerable GetAll(customerId, ...)
       {
         Order.GetAll(customerId,...); // The original static call.
       }
    }
    

    Now you inject this repository into your Customer class.

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

提交回复
热议问题