Technical Articles
Implementing an IoC Container in ABAP
This article was originally posted on DEV.to.
Preface
The following is an article describing my adventures of creating a naive implementation of an inversion of control container using the ABAP programming language.
The first part will focus on the Dependency Inversion Principle and ways of achieving loose coupling.
The second part will demonstrate how to use the IoC container with some highlights on it inner workings.
Part 1 – Dependency inversion
The key to a modular application is loose coupling.
Loosely coupled components usually makes changes easier potentially reducing maintenance effort while also allowing separation of concerns and isolation for unit testing.
The way to achieve loose coupling in OO applications is to adhere to the Dependency Inversion Principle (the D of SOLID).
Dependency Inversion Principle
he dependency inversion principle roughly states that:
high level components should not depend on low level components, but both should depend on abstractions.
Suppose our software consists of two cooperating modules, say module A and B.
If A uses some functionality of B, then A is dependent on B (i.e. B is a dependency of A).
This relation also means that functionality implemented in B is abstracted away from the point of view of A, thus B is at a lower level of abstraction.
Since A is calling B the flow of control also points in the same direction as the dependency, i.e. from A to B.
To resolve this dependent state between A and B we can introduce an abstraction layer (e.g. an interface) between the two components to flip the direction of the dependency.
By inserting the interface between the two components A will now depend on I (the abstraction) rather than directly on B while B will also depend on I (implementing the interface in this case).
The flow of control will still go from A to I to B, however the direction of the dependency will point against the flow of control in the relation of I to B.
This way both our components will depend on an abstraction rather than the high level component depending on the low level one.
This creates loose coupling, as we now can easily switch B to a different module, as long as we adhere to the contract defined by the abstraction I.
Dependency injection
Dependency injection is a way of putting the Dependency Inversion Principle into practice.
In order for our software to work we need to supply A with its dependency B without A knowing the concrete dependency.
If A is using B via an abstraction, but it is newing up B directly then the abstraction doesn’t serve it’s purpose, as A will still be tightly coupled to B.
To get the dependency to A we can use several techniques, which are collectively known as dependency injection. These (among others) could be:
- Constructor injection
- Property injection (a.k.a. Setter injection)
- Factories
- Inversion of Control containers
For the examples below I will use some variation of the following classes:
Constructor injection
When using constructor injection, the dependency is injected via a parameter through the constructor and stored as an attribute.
The following code example shows this in C#.
public interface IDependency { void LowLevelStuff(); } public class HighLevelModule { private IDependency _myLowLevelModule; public HighLevelModule(IDependency lowLevelModule) { _myLowLevelModule = lowLevelModule; } public void DoSomeStuff() { Console.WriteLine("I'll do some stuff"); _myLowLevelModule.LowLevelStuff(); } } public class LowLevelModule: IDependency { public void LowLevelStuff() { Console.WriteLine("In LowLevelModule"); } } public class AnotherLowLevelModule: IDependency { public void LowLevelStuff() { Console.WriteLine("In AnotherLowLevelModule"); } } public class Program { static void Main(string[] args) { var lowLevelModule = new LowLevelModule(); var highLevelModule = new HighLevelModule(lowLevelModule); highLevelModule.DoSomeStuff(); } } /* This code example produces the following results: I'll do some stuff In LowLevelModule */
Instead of the high level module creating its own dependency, it is supplied upon creation with it.
Since the high level module only knows about the abstraction (note the type of the attribute and the constructor parameter), it will not be tightly coupled to the concrete implementation.
Property injection
The idea of property injection is quite similar to that of the constructor injection, but instead of supplying the dependency during object creation, it can be set using a property or setter method.
Reworking the above example:
... public class HighLevelModule { private IDependency _myLowLevelModule; public IDependency MyLowLevelModule { set => _myLowLevelModule = value; } public HighLevelModule() { // Use LowLevelModule by default _myLowLevelModule = new LowLevelModule(); } ... } ... public class Program { static void Main(string[] args) { var highLevelModule = new HighLevelModule(); highLevelModule.DoSomeStuff(); var anotherLowLevelModule = new AnotherLowLevelModule(); highLevelModule.MyLowLevelModule = anotherLowLevelModule; highLevelModule.DoSomeStuff(); } } /* This code example produces the following results: I'll do some stuff In LowLevelModule I'll do some stuff In AnotherLowLevelModule */
Note that the property is public so it can be changed from outside the class.
It is also possible to have a baked in default dependency (as in the code above), which then can be changed during runtime using the property setter.
Factories
Another solution is to have a dependency factory, that supply an abstraction and use that in the constructor.
... public static class LowLevelModuleFactory { public static IDependency CreateModule() { return new LowLevelModule(); } } public class HighLevelModule { private IDependency _myLowLevelModule; public HighLevelModule() { // Use LowLevelModule by default _myLowLevelModule = LowLevelModuleFactory.CreateModule(); } ... } ... public class Program { static void Main(string[] args) { var highLevelModule = new HighLevelModule(); highLevelModule.DoSomeStuff(); } } /* This code example produces the following results: I'll do some stuff In LowLevelModule */
This is a solution somewhere between a constructor injection and a property injection.
It is typically also possible to configure the factory which concrete implementation it should create.
The advantage of using factories is that the object creation is localized inside the factory instead of being scatter throughout the application (see also Factory Method).
Inversion of Control containers
The idea behind Inversion of Control containers (or IoC containers for short) is to have an object that knows how to get hold of those dependencies that will be needed throughout the life of our application.
We configure the IoC container upon startup telling which concrete implementations it should supply and then leave the object creation to the IoC container.
The following example shows a way of doing it in C# using the Autofac NuGet Package.
... public class Program { private static IContainer Container { get; set; } static void Main(string[] args) { var builder = new ContainerBuilder(); builder.RegisterType<LowLevelModule>().As<IDependency>(); Container = builder.Build(); var highLevelModule = new HighLevelModule(); highLevelModule.DoSomeStuff(); } }
The container is configured to return
LowLevelModule instances for
IDependency.
Upon creating the
HighLevelModule the IoC container will realize that an
IDependency is needed which was not supplied and supply the constructor with a
LowLevelModule as configured.
An ABAP IoC Container
The constructor injection, property injection and factories can easily be implemented in ABAP as in any other OO language.
However — as far as I know — there is currently no standard solution for an IoC container in ABAP.
Since the ABAP language supports runtime type information via the Runtime Type Services (RTTS) it seems possible to implement an IoC container and in the second part of this article I will describe one way of doing it.
Part 2 – The ABAP IoC Container
The following class diagram shows the IoC container (click on the image to get a more detailed version).
The usage examples will be taken (in a somewhat modified form) from the unit tests created for the container.
These will use a set of objects that were defined for testing and demostration purposes.
The following class diagram shows these classes and interfaces.
Usage
To use the IoC container, first you must obtain an instance of it.
DATA(ioc_container) = zcl_ioc_container=>get_instance( ).
Objects can be registered in two ways into the container.
Simply by their name (
register method), or by an instance (
register_instance).
The
register method will create a mapping between an interface name and a class name.
Whenever this interface is requested from the container, it will assume that an instance of the registered class should be created.
The
register method will also do some checks for the registered class to see wether it can be instantiated, namely:
- If the class is
CREATE PUBLICor friends with the container
- If the class is instantiatable (i.e. not an abstract class)
If either of the above checks fail the register method will throw a
ZCX_IOC_CONTAINER exception with the text indicating the reason of the failure.
ioc_container->register( interface_name = `zif_ioc_b` class_name = `zcl_ioc_b_subcl` ). DATA(ioc_b) = ioc_container->resolve( `zif_ioc_b` ). cl_abap_unit_assert=>assert_bound( ioc_b ). cl_abap_unit_assert=>assert_true( xsdbool( ioc_b IS INSTANCE OF zcl_ioc_b_subcl ) ).
The
register_instance method can be used to register an object instance for a given interface.
If a registered instance exists for an interface name, then that instance will always be returned by the container.
This can be used for test double injection (as seen in the below example).
DATA(ioc_a) = CAST zif_ioc_a( cl_abap_testdouble=>create( `zif_ioc_a` ) ). ioc_container->register_instance( interface_name = `zif_ioc_a` instance = ioc_a ). cl_abap_unit_assert=>assert_equals( exp = ioc_a act = ioc_container->resolve( `zif_ioc_a` ) ).
Both
register and
register_instance have a corresponding
deregister and
deregister_instance method counterpart.
These methods can either be called with an interface name or without it.
Calling with an interface name will remove that specific mapping, while calling it without an input parameter will clear out all the registered mappings.
ioc_container->deregister( `zif_ioc_b` ). cl_abap_unit_assert=>assert_not_bound( ioc_container->resolve( `zif_ioc_b` ) ). ioc_container->deregister_instance( `zif_ioc_a` ). cl_abap_unit_assert=>assert_not_bound( ioc_container->resolve( `zif_ioc_a` ) ).
The method
resolve is used to get an instance of a registered interface (as seen in the above examples).
Since object creation issues are most likely already dealt with during the
register call,
resolve will not throw exceptions but simply return a
null object if the object creation fails for some reason.
The
resolve method can also be called directly with class names.
In this case no mapping is needed beforehand and the requested class will be instantiated.
DATA(ioc_b) = ioc_container->resolve( `zcl_ioc_b_subcl` ). cl_abap_unit_assert=>assert_bound( ioc_b ). cl_abap_unit_assert=>assert_true( xsdbool( ioc_b IS INSTANCE OF zcl_ioc_b_subcl ) ).
To see more examples of usage please check out the unit tests in the corresponding source code file.
Implementation
The mappings and registered instances are stored in hash tables, but the central part of the IoC container is the dynamic object creation done in the
resolve method.
For this I have used the Runtime Type Services (RTTS) which can give information about variables, types, method parameters etc. during runtime.
By using the object descriptor created based on the class’s name (
cl_abap_classdescr=>describe_by_name) we can get hold of the parameter list of the constructor method with all type information.
We can then iterate through the parameters and resolve them one by one.
Should an input parameter be a simple type, it can be created with an initial value.
And should it be an interface type, it can be (recursively) resolved by the IoC container itself.
The constructor parameters are collected in a parameter table which can be used with the generic object creation.
The complete source code can be found here.
Personal thoughts and improvement possibilities
This IoC container is far from being production ready.
I have made tests with a some “real world” classes as well and as far as I could tell it is quite stable, however I certainly did not do exhaustive testing.
I am also pretty sure that there’s room for improvement regarding performance.
All in all, the motivation of creating this IoC container was first and foremost curiosity.
Although as of now I have not used it in any complex application, I can see the possibility of using it instead of factory classes.
Suppose my application uses a set of utility classes.
Instead of having factories for all the utility classes, the IoC container could be used to supply the required instances.
When doing unit/integration testing the container can be preloaded with test double instances using the
register_instance method for test isolation.
The source code, along with the exception class, unit tests and the classes/interfaces created for the unit tests can be found in this GitHub repository (you should be able to pull the source code using abapGit).
In case you have questions or suggestions please feel free to reach out to me or open an issue or a pull request.
You can find me on twitter @bothzoli (DM’s are open).
Resources
I have learned a lot from the following resources about dependency injection, I gladly recommend them if you’re interested in this topic.
- Uncle Bob on the SOLID principles
- A great article by Martin Fowler on dependency injection
- Jeremy Clark’s Pluralsight course on dependency injection in .NET
I have used PlantUML to create the diagrams in this article.
Thank you for this very nice article. Is it possible to provide the github code in abapGit format so that to install/try it easily?
Thanks Sandra.
Unfortunately I don't have any experience with abapGit, but I'll try to do it, thanks for the tip.
I changed to use an online abapGit repository.
I'd suggest to switch to abapGit online repository. Then it's way more easier to install you repo and other people can easily contribute to your project.
Steps:
Thanks for the feedback.
I changed to an online abapGit repository, you should be able to clone it more easily now.
Great first blog. I have to think about that for a while 🙂 Thank you. It's perhaps a good addition to this section of the Clean ABAP style guide?
Thanks for the feedback Michael.
I'll send the article to the style guide folks so they may consider it.
Very nice! I can't wait for a good business reason to use it.
I too thought this was an excellent blog. It explained what an IOC container actually was, a concept I have been struggling with for years.
Last year in the online SAP course
about unit testing the presenters introduced the concept of "dependency lookup" which is quite similar. In that design a class can only be created as a returning parameter from a factory (i.e. no CREATE PUBLIC).
However that factory can get "injected" by a special injector class with a specific class that implements the interface and thereafter the factory returns an instance of the injected class. So in the SETUP method of your unit tests you inject one or more factories and the production code gets test doubles without knowing it.
The IOC concept seems very similar to me, except you do not need two separate classes (factory and injector) and the whole idea is more generic.
With the dependency lookup you need new factory and injector classes for each application, or have a monster factory class with hundreds of methods.
Could this be replaced by just one generic IOC class as described above? All the concrete classes would have to be "friends" with the IOC class so it could create instances of them, but that is the same as the dependency lookup approach.
There is bound to be a downside as well (there always is) but I cannot think of it just yet.
Are you familiar with the dependency lookup concept and if so how do you think it compares with the IOC concept?
Cheersy Cheers
Paul
Thank you very much for the kind words.
I am familiar with the dependency lookup concept and in fact, it was the very thing that sparked the idea of attempting to create a generic container.
When I was rewriting some of the earlier usages of constructor injection to dependency lookup, I noticed the huge amount of code that I just had to copy-paste when adding a new class to a dependency factory (and its injector (and their test classes)).
More precisely I felt the immense dullness of copy-paste with the occasional upsurge of cursing when I forgot to change just one small thing.
So I applied PDD (Pain Driven Development) and came up with what could be thought of as a stripped-down version of an IoC Container. It has an internal table to store references and has a GET_OBJECT and a SET_OBJECT method operating with class names and TYPE REF TO OBJECT to write/read it. It will call a parameterless constructor of the requested class but it can also be pre-filled with instances (or test doubles) if needed.
It lacks all the bells and whistles of being completely generic or doing the recursive resolution of importing parameters, but it serves very well in the restricted ways it is used (if it's interesting I'm happy to share more details about that as well).
Comparing the two, I think the dependency lookup serves it's purpose quite well and I'm not sure if the completely generic approach would be of significant benefit in the general case (my first and foremost reason for making it was simply curiosity).
However I can very well see a valid use-case for it. Suppose you have a full blown application, that gets its dependencies via this container. You'd need to register the dependencies at an entry point of the application (or maybe in a customising table of some sort). Suppose also that all your DB layer operations are separated -- as they should be -- in repositories. Now you can easily do integration testing, by setting up the container to return mock objects for the repositories, but use the "real" implementations anywhere else. This could be achieved by providing a hook in the entry point (see Template Method Pattern) or changing the underlying customising. Thus you can test the whole application with fake data with the push of a button.
Regarding downsides, I can think of multiple 😀
You asked about replacing the dependency lookup factories with one IoC container. That would also mean one class, that is friends with everybody in your application, possibly overarching multiple packages. This in and of itself may not be an issue, however for me it just smells. So much so, that I already addressed it, with the ZCL_IOC_CONTAINER_ABSTRACT, that can be inherited from (ZCL_IOC_CONTAINER_SUBCLASS) to have multiple containers maybe per package or per layer.
Another downside is performance. I did not do extensive performance measurements, but with the very-very-very simple test I did, it seems quite a bit slower. We're still in the microsecond range, but it's worth noticing anyhow.
A third downside I can think of, is type safety. There are just sooo many generic stuff going on that I have a fear that I didn't cover all the possible edge cases, and a cast exception somewhere would bring the whole thing to its knees. Although this could also be mitigated by adding unit tests for all the interfaces/classes one might would like to use with the IoC container (a practice that I would encourage anyways).
My answer became quite long, sorry about that, but hopefully I answered all your questions.
Cheers,
Zoli
I was watching videos to learn design principles using C# language and came across the IoC Container which I have never heard of. This is a great feature in C# and widely used and it has different number of IoC containers and to name a few
Then I searched SDN for ABAP IoC Containers and found this. It is good to see ABAP also has got one to start which can be improved over the time. If anyone interested to see the internals of how IOC Container works here is the video Demystifying Dependency Injection Containers
Regards,
Yellappa.