boost-ext / di

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

Different injectors create same singleton shared_ptr #431

Closed Warchant closed 4 years ago

Warchant commented 4 years ago

Expected Behavior

Different injectors should create different singletons (std::shared_ptr).

Actual Behavior

Different injectors create same singleton (std::shared_ptr).

Steps to Reproduce the Problem

https://godbolt.org/z/qVF9TI

In this example, Impl should have been created 2 times, because we use 2 different injectors.

Specifications

Warchant commented 4 years ago

@krzysztof-jusiak

krzysztof-jusiak commented 4 years ago

Thanks, @Warchant for your bug report and the example :+1:

By default (due to performance reasons) a singleton (global per app scope) is used.

In order to get shared per injector scope a shared scope has to be used:

        boost::di::bind<Interface>.to<Impl>().in(boost::di::extension::shared) // shared per injector

Full example here -> https://wandbox.org/permlink/4D4GXnqyPGijJb5X

More information might be found:

Please also notice that you can also change the default behaviour (for shared scope to be a default one) by

    auto injector = di::make_injector<di::extension::shared_config>(...);

Example here -> https://wandbox.org/permlink/4D4GXnqyPGijJb5X

I hope that makes sense.