boost-ext / di

C++14 Dependency Injection Library
https://boost-ext.github.io/di
1.17k stars 140 forks source link

Different Injectors that use the same bindings would unexpectedly share the same singletons #289

Closed lyn444 closed 6 years ago

lyn444 commented 6 years ago

Expected Behavior

Different injector instances should never share the same singletons on object creation.

Actual Behavior

If the bindings are the same they will share the same singletons.

Steps to Reproduce the Problem

class A
{
public:
    A()
    {
        std::cout << "A is created." << std::endl;
    }
};

int main()
{
    {
        auto injector = di::make_injector(
        );

        A& a = injector.create<A&>();
    }

    {
        auto injector = di::make_injector(
        );

        A& a = injector.create<A&>();
    }
    return 0;
}

In the code above, A is only created once, but it is expected to be created twice.

However, if the bindings are not the same, it will be expected and created different object.

class A
{
public:
    A()
    {
        std::cout << "A is created." << std::endl;
    }
};

class B
{

};

int main()
{
    {
        auto injector = di::make_injector(
        );

        A& a = injector.create<A&>();
    }

    {
        auto injector = di::make_injector(
            di::bind<B>().to<B>()
        );

        A& a = injector.create<A&>();
    }
    return 0;
}

Specifications

lyn444 commented 6 years ago

apparently using scoped_scope solves this issue but the original question is still quite confusing. I think they are expected to behave consistently but obviously it does not with different bindings.

kris-jusiak commented 6 years ago

Thanks, @lyn444.

Right, [Boost].DI 1.x.x is using a singleton scope by default. So, references life time is being bound to the life time of the application. Since, shared, scoped scopes bind the injector instead the life time of created references equals the life time of the injector object.

For [Boost].DI 2.x.x the defuault scope of the injector will be changed to a scope which bounds the life time to the injector.