Posts in "IoC/DI Framework" category Dependency Management: A More Detailed Look

My previous post glanced over the details behind the dependency management framework that I have started to build. However the intention of this post is to rectify that and go through the core parts of the code in more detail. Hopefully giving you a better idea of how it currently works.

There are two main parts to the solution; the Container and the IHasDependencies interface.

The Container

The Container class is responsible for providing an instantiated class when a particular interface is requested. The container class uses an internal map to know which classes map to which interfaces, this map is what gives the users the flexibility to change dependencies without changing code as everything is controlled from it’s contents.

Users are provided with two ways to build the map in the Container; either programmatically or via an external mapping file. To programmatically add a mapping simply call the addMapping method passing in a ClassMap. The ClassMap expects Type parameters for the interface and class that you want to add; this is to try and make the code clearer and remove the chance of typos messing things up. To load up the map using an external mapping file a simple call to loadMappFile passing in the name of the static resource that is the file will populate the map. The map file itself is currently just a JSON representation of a ListI had to use a different class as you can’t deserialize the Type class – although as you can see from the code ultimately the ClassMapFileEntry is used to populate a ClassMap class before being added to the map.

There are two ways to build the map as I think they lend themselves to different use cases: the programmatic method being great for quickly pulling together some mock classes in a test scenario, whilst the mapping file gives much more flexibility at runtime or when moving code between environments. There are clearly crinkles in this to work though – multiple mappings for the same interface, conditional mappings, ensuring the class implements the interface it’s mapped to are just a few that fall off the top of my head.

Given the map the container is now in a position to provide users with the classes they need for given interfaces and it is the getClass method on the container that provides this functionality.

This method is probably a bit longer than it needs to be at the minute but cutting through the chaff you can see that it can be broken down into three basic functions:

  • get the name of the class needed from the map
  • instantiate the class
  • get any dependencies that class requires

Whilst the heart of the users experience this is the simplest part of the whole solution in my mind. Getting the classname form the map is self explanatory. The instantiation makes use of the JSON parser trick to get the class; the only thing to remember here is that the constructor of the class isn’t called. And the final part, getting dependencies, is really just a recursive call to this method: rinse and repeat. OK it’s a little more involved than that but not much and falls nicely into the next section.


One of my biggest goals at the outset of this process was to not have to worry about child classes and their dependencies. I want to be able to say to the container: “give me a working one of those – and don’t bother me with how”. This is where the simple IHasDependency interface comes to the rescue.

As you can see the interface is extremely simple. The key to the process is the map returned but getDependencies; the key set of the map is used by the container to know which interfaces to request classes for in the recursive call. The values are where the container puts the instantiated classes to pass back to the class requesting the dependencies. This works because non-primitive types are passed by reference. It would obviously be possible to have a member on the interface that was this map but we would run into problems with being able to populate it in classes that are instantiated via the JSON trick.

The second method in the interface is gotDependencies and at first look seems a bit odd. Looking back at the container class you can see that this method is called after all of the dependencies have been resolved and populated in the map. So, why is it called? It is there to give the class implementing the interface the chance to take it’s new found classes out of the map and assign them to internal members; after all no one wants to be referencing members from a map it just feels ugly – although if that’s what you want then knock yourself out!

An example of a simple class that implements the IHasDependencies interface would look something like this.

This class has a dependency on a IHttp implementation. To declare that it has this dependency it implements the IHasDependencies interface. In the getDependencies method is creates a new map and adds to it the interfaces for which it needs concreate classes, in this case it’s just IHttp. This now means that when the container instantiates the ParentClass class it will know it has dependencies that need full filling (the IHasDependencies interface) and by calling the getDependencies method the container is able to get a list of required interfaces and can populate the map to return them to the ParentClass.

You can also see in the ParentClass the implementation of the gotDependencies method; in this the IHttp class in the map is assigned out to a private member of the ParentClass class to allow it to be easily used elsewhere in the class.

Bringing it all together

Getting a fully loaded ParentClass is a simply a case of loading a map and then requesting the class from the container.

Two simple calls and obviously for each extra class you need it’s just a case of a call to getClass. There is some overhead associated with this in that you need to a build an maintain your mapping file and that you need to instrument your classes with the IHasDependencies interface but rarely do you get something for nothing.

What you go get however is a nicely de-coupled code base. And not only that it actually starts to become quite readable; getting a class with all necessary dependencies is one call in your code, all classes with dependencies are clearly labels and list all dependencies in one common place and the mapping is held in a centralised location. For me this framework looks like it will meet my needs.

Having said that I also think there is still work to be done; this is very much the seed of the idea and I think there are lots of improvements to be made as well as bells and whistles to add.

The project can be found on Github feel free to dive in and hack about with it. Dependency Management: A First Pass

I’m starting to sound like a broken record I’m sure – constantly going on about why we should be using interfaces in Salesforce more, why we should be breaking tightly couple code blah blah… Go here and here if you haven’t already been exposed to my rabbiting!

Now, I don’t just write this stuff I try and make sure I live by my own word as much as possible. But, as I’m sure you all of you that have tried to decouple things more in Salesforce, this decoupling can quickly become a mess: making sure the right concrete class is being called at the right time is only simple at first. It’s the same old story: at the time everything makes sense but going back to that code one, two, three months later and you sit there thinking: “what the hell was I on when I wrote this?”

It was such a moment earlier in the week that led me to face up to the challenge I set myself a while ago and do something about the way in which I managed interfaces and dependencies in my code. With the overall goal of building a framework to manage all of this in a clean and repeatable way. I may well find that this has been done before but it has been a wet Sunday and wanted to have a stab at it myself.

So – looking to other languages the obvious answer is to tend towards some kind of dependency injection, inversion of control or service locator – but which one and why? Well, they’ll all similar but different and frankly an in depth discussion about which to use and why is way beyond the scope of what I wanted this post to be. Suffice to say I believe I have gone for a form of interface dependency injection with some kind of inversion of control container – if all of that seems a bit vague then it’s because it is; I’m not really one for theory and names so please excuse any incorrectness there.

The Solution

Also I’m not going to post all of the code here as I don’t think it’s appropriate but if you want to follow along as I go through/around the various components then the project can be found on Github.

The platform provides a big challenge for dependency injection as there’s no form of reflection or inspection – it’s for this reason I have decided to adapt interface injection. Constructor based injection could have been an option but the novel method used to dynamically instantiate classes means that there’s no construtor that I can inject into. At the heart of this system is the interface IHasDependencies: any class that you want to have dependencies injected into it by the container needs to implement this interface. Using the interface means that this is the only thing the class developer needs to be aware of; this keeps the classes decoupled and unaware of the container that’s wiring them up.

As you can see the interface is very simple with only two methods. The first, getDependencies, returns a Map describing the dependencies that the class requires. A map is passed as it allows me to make use of the fact that non primitive objects are always passed by reference on the platform – this means that the container can populate the value portion of the map with the concrete classes and they get automatically “passed” back to the class that needs them. This little trick means we can again keep everything nicely decoupled.

The second method, gotDependencies, is a little bit of a hack but a necessary one. The container calls this once it has set all of the values in the map to concrete classes allowing the class wanting the dependencies to assign them out to members as it sees fit. This has to be done this way as without reflection/inspection the container cannot do it itself.

The other major part of this solution is the Container class. This class is responsible for maintaining a mapping of interfaces to concrete classes and then providing the appropriate concrete class when needed. The container calls itself recursively to get hold of all of the dependencies in all of the child classes as well. This recursion means that the consumer of the parent class need not worry about what other classes may or may not need to be configured in order to get a complete object graph. The container is able to seemingly dynamically instantiate classes but is in fact using the, probably now well documented and, extremely useful quirk of the JSON deserializer as described in much more detail here.

The rest of the functionality in the container class is to control the all important mapping. There are two available methods to setup the mapping: the first is a code based solution where you programatically add the interface to concrete mapping; this is useful in a test scenario where the mocks are likely to be one off test classes. The second method allows you to load the map up from a text file stored as a static resource. The file is currently structured as a simple JSON string representing a list of Container.ClassMapFileEntry objects. This approach gives you the ability to change functionality without deploying code – useful if you’re working in an environment where this can be an arduous process and also very handy for changing behaviour, such as integration points when moving code between environments as again no code needs to be changed between environments.


This post is short and lacking in any in-depth code walk through on purpose as I really just wanted it to be a marker, an introduction to what I hope will be an interesting discussion around the worthiness of this idea and how it can be improved (or a signpost to an existing fully fledged framework). There are plenty of features that I can think of – conditional mapping and instantiation control to mention just two – that could be added to this. Not to mention a whole bunch of error handling and test classes. But I feel that all of that is further down the road, the core of the solution needs to be well developed and debated first.

As I mentioned before, all of the code that I have so far can be found on Github and I encourage you to take a look, have a play and let me know of it’s many flaws. I include a couple of examples below that work with that code to exercise the basics of the container and interface – hopefully they will give you some idea of how it’s meant to be used. In the meantime I will work on a follow up post that goes through all of this in much more detail and breaks the code down section by section.

Looking forward to your thoughts.

I’ve had a stab at coming up with a way to manage dependent interfaces; a very simple IoC/DI solution for – I’m looking for ways to improve it and appreciate feedback. The code can be found over here.

I have added a bit more of a detailed walk though here