Friday, 20 November 2009

To inject or not to inject, that is the question

When trying to implement the specification and implementation for scheduling a check, I had the problem of what method to use for sending the event.
There are basically two options:
  1. Inject a Bus
  2. Use a static/well known object for sending the event.
Lets take a look at both options...

Inject a bus

When Injecting a bus (or an other service) the Host will need a variable/field that holds the implementation of the service. Somehow the real implementation should be injected into the object. Normally we will do that by using a framework like structuremap or some other Dependency Injection framework.
But we have the problem that Host is an Entity which we will not instantiate ourself, but we ask our repository. So there will be another place where we need to inject the right service and I think this will lead us to duplicate code.

Use static object

Using a static object would be much simpler. We have one object that sends all events to the right place. How the event handlers are registered depends on the architecture of the application, but basically this will be done via an Dependency Injection framework. This method is explained more deeply by Udi Dahan.


Injecting services into entities is just to complicated and in my opinion should be avoided.
Using static classes as services should also be avoided, because it will make testing more difficult.

So what do we use? I will choose for the static class, because it only routes the actual events to the right handler, it will be easy to implement and it will be easy to use it in tests. Other services should be non static classes so that it follows the normal object oriented philosophy.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.