Skip to content

yekhlakov/container

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 

Repository files navigation

"DI" container

In c++ we cannot (yet?) have a fully functional dependency injection container like in php, but we may try to get one.

Features

The container contains a set of singleton instances of required classes. These instances can be retrieved at any point in the program. So ideally the container class itself should not be a template class so we can pass it around by reference.

The container controls the lifecycle of these singletons, so we don't have to manage it manually.

The container cannot provide a complete DI solution due to lack of proper reflection capabilities in c++, but at least it can inject itself in the constructor of the class being registered (if the constructor takes a reference to the container in the first argument).

Usage

Just #include "container.h" wherever it is needed.

Create a container:

maxy::control::Container c;

Let's observe a very simple class:

struct Pod
{
	Pod ()
	{
		// ...
	}
};

We may put it to the container as simply as this:

c.add<Pod> ();

and then retrieve a reference to the singleton instance of our Pod.

auto & x = c.get<Pod> ();

Obviously if we try to get an instance that was not previously registered, we get an exception.

Also worth noting that our singletons should have their copy constructors deleted in order to prevent their occassional duplication like this:

auto duplicate = c.get<Pod> ();

Now consider a more complex class like the following

struct PodWithInt
{
	PodWithInt (int n)
	{
		// ...
	}
};

Registering this class in the container is pretty straightforward: we just pass the required arguments to the container and it then forwards them to the instance constructor.

c.add<PodWithInt> (666);

The class constructor may also take the container itself:

struct PodWithContainer
{
	PodWithContainer (maxy::control::Container & c)
	{
		// ...
	}
};

This is registered the usual way:

c.add<PodWithContainer> ();

Note that the reference to the container will be injected automatically (because DI).

Finally, there can be more arguments to the constructor than just a container reference:

struct PodWithContainerAndMore
{
	PodWithContainerAndMore (maxy::control::Container & c, float r, int x)
	{
		// ...
	}
}; 

These arguments must be provided at registration:

c.add<PodWithContainerAndMore> (66.6f, 666);

Check test.cpp to see it all in action.

About

"DI"-like container

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages