1

Following my previous question, I would like to achieve the following with minimum boilerplate code. I understand that Kangaru has autowiring feature to reduce code. Here the original working version of the code.

#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::overrides<IBService>  {};

void main() 
{
    kgr::container container;

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

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

I have tried the following struct BService : kgr::single_service<B, kgr::autowire>, kgr::overrides<IBService> {}; but it does not work well for me

Y.H.Cohen
  • 41
  • 7

1 Answers1

0

I have also posted the question in the Kangaru chat, and the author answered to me the following and it works well

#include <kangaru/kangaru.hpp>
#include <iostream>

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

struct A : IA
{
    A()
    {
        std::cout << "Ctor A" << std::endl;
    }

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


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

struct B : IB
{
    IA& _a;

    B(IA& a)
        :
        _a(a)
    {
        std::cout << "Ctor B" << std::endl;
    }

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

auto service_map(IA const&) -> struct IAService;
auto service_map(A const&) -> struct AService;
auto service_map(IB const&) -> struct IBService;
auto service_map(B const&) -> struct BService;

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

struct AService : kgr::single_service<A, kgr::autowire>, kgr::overrides<IAService> {};
struct BService : kgr::single_service<B, kgr::autowire>, kgr::overrides<IBService> {};

void main()
{
    kgr::container container;

    // configure which abstract service will be used
    container.emplace<AService>();
    container.emplace<BService>();

    // Use the abstract serivces
    container.service<IAService>().run();
    container.service<IBService>().runB();

    container.invoke([](IA& a, IB& b) {
        a.run();
    b.runB();
        });
}
Y.H.Cohen
  • 41
  • 7