Andrew Stephens
Andrew Stephens

Reputation: 10193

Dependency Injection and internal helper classes

I use Castle Windsor, but I guess this applies to all DI containers...

I often find myself creating internal helper classes and injecting these into other classes. (Actually Windsor doesn't support internal ctrs so I typically end up making the helper classes public, which is my first "code smell").

The helper class may have a number of dependencies of its own, of types already registered with Windsor, so it makes sense (to me) to register the helper class with Windsor too, so I can inject it into the classes that need it. E.g.

public MyService : IService
{
    public MyService(MyHelper helper, other dependencies...)
    {
    }
}

After reading a few articles I'm starting to wonder if this is "misusing" Windsor, or just generally bad code design. If that's the case, how should I deal with helper classes?

Upvotes: 6

Views: 7224

Answers (2)

Steven
Steven

Reputation: 172646

I often find myself creating internal helper classes and injecting these into other classes.

This is a common refactoring technique called Facade Services:

Facade Service hides the aggregate behavior behind a new abstraction.

As for your question about internal classes:

making the helper classes public, which is my first "code smell").

Not at all. There is nothing smelly about public classes. If you follow the rule "program to interfaces" there is no problem if the implementation is public. This simplifies testing, since unit tests will depend on the class directly.

Long story story, you are not misusing DI or a DI Container. If you are encapsulating the behavior inside the helper class, you are doing the right thing. Hard thing however is to find out what the best way to encapsulate behavior is in a way that makes sense from a business perspective. But while doing so, it might lead you to new insides and new business concepts.

Upvotes: 7

Chima Osuji
Chima Osuji

Reputation: 391

it makes sense (to me) to register the helper class with Windsor too, so I can inject it into the classes that need it

Spot on :)

Dependency injection is a technique where one object supplies the dependencies of another object.

It makes no difference if the dependency is an interface or a class (or a string, or an int...) - it is still a "dependency". Helper or utility classes are very common aids, but you may find it useful to program to an interface, as for example this means we can mock them for testing purposes, or substitute one implementation for another without affecting the services that depend upon them.

Upvotes: 1

Related Questions