|
Minimal Dependency Injection Framework for C++
Single file library for implementing the dependency injection pattern
|
This is a single file library for implementing the dependency injection pattern in C++, a technique for achieving dependency inversion:
instead of:
The library is declared within the dip namespace. To import the library:
There are no interfaces in C++. A service must be declared as an abstract class having a virtual destructor. For example:
Service providers are implemented as non-abstract descendants of services. For example:
A single service provider may implement multiple services thanks to multiple inheritance, but this is not recommended:
There are two service consumption modes:
dip::inject*() methods are consumed using dip::instance<Service>. Just one service provider can be injected and consumed. See InjectionExample.cpp.dip::add*() methods are consumed using dip::instance_set<Service>. Many service providers can be injected and consumed. See ProviderSetExample.cpp.If you want to use both modes simultaneously (for the same service), you have to inject the service provider twice using dip::inject*() and dip::add*() methods.
Service consumers retrieve instances of a service provider by declaring them. Depending on the consumption mode:
dip::instance<Service> service_provider; ordip::instance_set<Service> service_provider_set;The lifecycle of the service provider instance is automatically handled in a similar way to std::unique_ptr, but service provider instances are not moveable.
To make use of a service provider instance just call a (virtual) service method using pointer syntax. For example:
dip::inject_transient<Service,Provider>(constructor parameters) or dip::add_transient<Service,Provider>(constructor parameters) depending on the consumption mode.dip::inject_singleton<Service,Provider>(constructor parameters) or dip::add_singleton<Service,Provider>(constructor parameters) depending on the consumption mode.dip::inject_thread_singleton<Service,Provider>(constructor parameters) or dip::add_thread_singleton<Service,Provider>(constructor parameters) depending on the consumption mode.[!CAUTION] A service provider can consume instances of another service, but this could lead to circular references. Be very careful. See InfiniteLoopExample.cpp
An injector is an instance of dip::Injector<Service> having two std::function members:
Service *acquire():nullptr.void release(Service *instance)instance is a raw pointer to a service provider instance previously retrieved via acquire(). Note that this pointer is Service *, not Provider *. The injector should typecast this pointer to the service provider class.To provide a custom injector for a service:
Example applications: