boost-ext / di

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

Although it's unique scope injector.creates a singleton #432

Closed subbota-a closed 4 years ago

subbota-a commented 4 years ago

Consider the following example.


class server {};

int main()
{
    di::injector<client> injector = di::make_injector(
        di::bind<server>().in(di::unique)
    );
    std::shared_ptr<server> server1 = injector.create<std::shared_ptr<server>>();
    std::shared_ptr<server> server2 = injector.create<std::shared_ptr<server>>();
    assert(server1);
    assert(server2);
    assert(server1.get() != server2.get()); // assert failed!
}

```## Expected Behavior
I expect that if I use 'unique' I get two different servers. 
kanstantsin-chernik commented 4 years ago

It is a bit confusing but it actually doesn't user unique scope binding in this case. If you call it with injector.create<std::shared_ptr<server>> it uses default shared scope. You can try to forbid unbound instantiations and this code will fail as there is no bound shared scope.

subbota-a commented 4 years ago

I'm sorry but your answer isn't clear to me. So, how to get two different 'server' instances if I want shared_ptr?

kanstantsin-chernik commented 4 years ago

You need either to bind it in shared scope (an extension) or use shared_config to override default behavior from singleton to shared. Of course nothing stops you from doing both.

Here is an example

subbota-a commented 4 years ago

Hi, @kanstantsin-chernik ! I was a bug in my example! I wrote di::injector<client> instead of di::injector<shared_ptr<server>> I just wonder why does the injector create me a server though