Home > Mobile >  How to use C Kangaru IOC library
How to use C Kangaru IOC library

Time:01-03

I'm trying to do some basic stuff with the kgr library but to be frank it is not so intuitive.

As you will see I have 2 interfaces and 2 concrete classes. The B concrete class should receive by injection in its ctor the registered instance of IA interface.

  1. What's wrong there.
  2. Is the dependency definition is mandatory or kgr is capable to 'guess' it?
#include <kangaru/kangaru.hpp>
#include <iostream>

struct IA
{
    virtual void run() const = 0;
};

struct A : IA
{
    void run() const override
    {
        std::cout << "A" << std::endl;
    }
};


struct IB
{
    virtual void runB() const = 0;
};

struct B : IB
{
    IA& _a;

    B(IA& a)
        :
        _a (a)
    {}

    void runB() const override
    {
        std::cout << "B" << std::endl;
    }
};

struct IAService : kgr::abstract_service<IA> {};
struct IBService : kgr::abstract_service<IB> {};

struct AService : kgr::single_service<A>, kgr::overrides<IAService> {};

struct BService : kgr::single_service<B, kgr::dependency<IAService>>, kgr::supplied  {};

int main() 
{
    kgr::container container;

    container.service<AService>();
    container.service<IAService>().run();

    container.service <BService>();
    container.service<IBService>().runB();
}

This is the code I have run.

container.service<IBService>().runB();

causes an abortion of the program.

CodePudding user response:

struct BService : kgr::single_service<B, kgr::dependency<IAService>>, kgr::supplied  {};

should be

struct BService : kgr::single_service<B, kgr::dependency<IAService>>,
                  kgr::overrides<IBService>
{};

Demo

  • Related