Infector++ is a lightweight IoC Container for doing dependency injection, it was designed to be easy to use and hard to misuse.
Note for VisualStudio users: due to a VisualStudio bug, "std::unique_ptr" can't be used properly with Infectorpp. I hope they fix that soon, in the meanwhile, VS users could still inject quietly "std::shared_ptr".
Thanks! :)
- Exception safety (STRONG GUARANTEE)
- Virtually remove memory leaks
- Lightweight and simple
- No compilation (few headers only)
- Clean API
- Typesafe
- Non-intrusive (constructor injection without code generation)
- Lazy instantiation (everything is created only when needed)
- C++11 (requires GCC 4.6 or greater, Clang 3.0 or greater, VisualStudio 2013 Update 4 CTP)
- No macro obscure magic
- No string processing
Version 1.0.3 released! (changelog.txt) checkout new bugfixes and improvements!
Given the following class diagram (your existing code design):
You list your composition needs:
- BedRoom implements IRoom
- ComfortableBed implements IBed
- BedRoom has 1 (and so depend on) IBed
Since BedRoom depends on a IBed and inherits IRoom, the class will look like this
class BedRoom: public virtual IRoom{
std::unique_ptr<IBed> myBed; //unique pointer, there's a different bed for each room
public:
BedRoom( std::unique_ptr<IBed> bed )
: myBed( std::move(bed) ) // take explicit ownership
{ }
};
In your main()
you create your IoC Container,
Infector::Container ioc;
then bind implementations to their interfaces,
ioc.bindAs<BedRoom, IRoom> (); //bind BedRoom as IRoom
ioc.bindAs<ComfortableBed, IBed>(); //bind ComfortableBed as IBed
and finally wire a constructor for concrete types
ioc.wire<ComfortableBed >(); //ComfortableBed constructor has no arguments
ioc.wire<BedRoom, IBed>(); //BedRoom takes 1 IBed as argument
Just simple as calling build
on the IoC Container,
auto myRoom = ioc.build<IRoom>();
The instantiated room is a BedRoom, it has a IBed (the Comfortable one). The type "hided" by auto is
std::unique_ptr<IRoom> myRoom;
and no call to "std::move" is necessary because move constructor in this particular case is automatically called.
- The creator of this lightweight IoC container for Unity, in particular his articles about the topic are very usefull:
- Lightweight IoC Container for Unity3D - part 1
- Lightweight IoC Container for Unity3D - part 2 Infectorpp was heavily inspired by that Container.