HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Using Poor Man's DI to inject helper class dependencies

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
helperpoorinjectusingmanclassdependencies

Problem

I had a rather large method in one public class that I refactored into 2 helper classes. The thing is though, that those 2 helper classes have dependencies. I refactored them into helper classes so I could mock and test them easily, which worked out perfectly.

However, the thing is I don't want to have to register my helper classes in the DI container, because I know the public class will always be using those specific implementations.

This is how I implemented the public class' constructors:

/// 
    /// Internal constructor used by tests for mocking.
    /// 
    internal TranslationCompiler(ITranslationCatalogTransformer translationCatalogTransformer, ICompiledCatalogTransformer compiledCatalogTransformer)
    {
        if (compiledCatalogTransformer == null) throw new ArgumentNullException("compiledCatalogTransformer");
        if (translationCatalogTransformer == null) throw new ArgumentNullException("translationCatalogTransformer");
        _translationCatalogTransformer = translationCatalogTransformer;
        _compiledCatalogTransformer = compiledCatalogTransformer;
    }

    /// 
    /// Public constructor that passes dependencies to concrete implementations of helper classes.
    /// 
    public TranslationCompiler(IResourceService resourceService, ITranslationSerializer serializer)
    {
        if (resourceService == null) throw new ArgumentNullException("resourceService");
        if (serializer == null) throw new ArgumentNullException("serializer");
        _translationCatalogTransformer = new TranslationCatalogTransformer(resourceService);
        _compiledCatalogTransformer = new CompiledCatalogTransformer(serializer);
    }


Is this an acceptable use for poor man's DI? This way, the DI container only has to know the actual dependencies for the public class to work, while still being very testable.

Solution

I don't see anything wrong with your implementation - if it works for you, and does not interfere with the system - go for it!

I will even go further and claim that the guard conditions in your internal constructor are redundant because the constructor will only be used by the single public constructor, or by a test which:

  • Either counts on the helper - in which case a NullPointerException will occur and fail the test, or



  • Does not need the helper, in which case there is no need to mock it...



Final note: I guess that the public constructor actually uses resourceService and serializer in some code you deleted from it, otherwise, the guard conditions there are also redundant...

Context

StackExchange Code Review Q#48129, answer score: 3

Revisions (0)

No revisions yet.