Poor man's Dependency Injection. Feasible?

dependency-injection
nservicebus

(Philipp Dolder) #1

Due to tons of bad experience with using DI containers in the past we’re thinking about a poor man’s solution using factories. That’s all good and easy so far, except when it comes to integration with NServiceBus to create the message handlers.

As I understand currently. I would need to build a custom implementation of ContainerDefinition and ending up building my own IContainer implementation which will connect NServiceBus with our handler factories.

Is this something you would consider feasible to do, or do you have experience/reasons against this approach?
If it’s a feasible way: Is my understanding of how to achieve this correct?


(Daniel Marbach) #2

Hi Philipp

I don’t think you require to build your container definition to be able to use poor man’s DI. How about doing the following

public class RequestDataMessageHandler :
    IHandleMessages<RequestDataMessage>
{
    static ILog log = LogManager.GetLogger<RequestDataMessageHandler>();

    public RequestDataMessageHandler() : this(new MyDependency("Test"))
    {
    }

    public RequestDataMessageHandler(MyDependency dependency)
    {
    }
}

NServiceBus will call the default parameter less constructor. In that constructor you now up all the things you need and pass it to the constructor that has the parameters for all the dependencies. You could even make the second constructor internal and add internals visible to attribute to the assembly for the tests. Would that work for you?

Daniel


(Philipp Dolder) #3

Hi Daniel,

thank you, this will work like a charm for every scenario that comes to mind so far.

the log field is a static because of performance reasons, as I understand, right?

Philipp


(Daniel Marbach) #4

Hi Philipp

I added a static log field because that is mostly how loggers get initialized in popular frameworks. You could also inject a logger if required for example if you want to test log statements. If you are using the NServiceBus abstraction with logging you can even test it when the handler has static fields

https://docs.particular.net/nservicebus/testing/#testing-logging-behavior

Have a good weekend

Daniel