Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I\'m using an ORM which doesn\'t allow me to inject dependencies in the construc

ID: 642854 • Letter: I

Question

I'm using an ORM which doesn't allow me to inject dependencies in the constructor. Let's say I'm using DDD for the business logic, and the MVC pattern for the UI. Now one of my domain objects needs to access an external service. I'm very opposed to the service locator anti-pattern (wouldn't touch it with a ten foot pole), but as I see it, that leaves me with the following: class Controller { private readonly IExternalService _externalService; public Controller(IExternalService externalService) { _externalService = externalService; } public ViewResult Action(Guid Id) { // Omitted repository access for brevity. domainObject.DoSomethingWichNeedsAnExternalService(_externalService); } } Somehow I get the feeling this isn't very clean, what if the "domainObject" is buried deep into the model/graph, should the "_externalService" be passed all the way down? Are there any best-practice alternatives?

Explanation / Answer

It seems like it will get out of hand. For instance, I had to use an IRealTimeClockService to inject into my units under test so that I could have repeatable test results for things that depend on the system time. That seems like a lot of weight for a service that just calls DateTime.Now. But I must admit that it really hasn't made the code less readable, even though you have to pass it to base class constructors too.

In some ways it's better because it's obvious what your dependencies are.

If you do have a lot of dependencies injected into an object, that might mean you're violating the single responsibility principle, and that class could be broken up into something that does two unrelated things.

On the other hand, if you have a complex system, you will have complex objects with lots of dependencies. I think it's better to be explicit about it.

Something to consider: if your class A takes 5 dependencies and passes 4 of them on to a helper object without touching them, perhaps you should just replace those 4 with a dependency on the helper object (or an interface, obviously).