DEV Community

bothzoli
bothzoli

Posted on • Updated on

Implementing an IoC Container in ABAP

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

The 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.

Dependent Modules

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.

Dependent Modules with Abstraction

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:

Dependency injection

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
*/
Enter fullscreen mode Exit fullscreen mode

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
*/
Enter fullscreen mode Exit fullscreen mode

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
*/
Enter fullscreen mode Exit fullscreen mode

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>();
    builder.RegisterType<HighLevelModule>();
    Container = builder.Build();

    var highLevelModule = Container.Resolve<HighLevelModule>();
    highLevelModule.DoSomeStuff();
  }
}
Enter fullscreen mode Exit fullscreen mode

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).

IoC Container class diagram

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.

Test classes class diagram

Usage

To use the IoC container, first you must obtain an instance of it.

DATA(ioc_container) = zcl_ioc_container=>get_instance( ).
Enter fullscreen mode Exit fullscreen mode

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 PUBLIC or 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 )
).
Enter fullscreen mode Exit fullscreen mode

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` )
).
Enter fullscreen mode Exit fullscreen mode

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` )
).
Enter fullscreen mode Exit fullscreen mode

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 )
).
Enter fullscreen mode Exit fullscreen mode

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.

I have used PlantUML to create the diagrams in this article.

Top comments (0)