boost-ext / di

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

Override default deduction policies. #447

Closed bkuhns closed 4 years ago

bkuhns commented 4 years ago

I'm looking into using session and/or shared scopes with boost.di to replace manually injected code.

In general, my manual injections don't agree with di's default scope deduction. Rather than having to specify custom .in() scopes for every single binding when creating injectors, it would be nice if there were a way to specify custom deduction behaviors to be used with all bindings when creating an injector.

For example, const T& gets deduced to global/singleton scope by di, but I would like to make all const T& use session scope. However, if another class takes std::unique_ptr<T> (same T) in its constructor, I want unique scope to be used.

I don't see how I can specify both session and unique scopes to the same type.

kanstantsin-chernik commented 4 years ago

@bkuhns you have you own config and override scope deduction. Follow the example of shared_config

However, if default scope is unable to construct whatever you think it should you might also need to implement your own scopes which will construct the stuff you want. It sounds like a lot of hustle but it is quite straightforward to do. Good luck!

bkuhns commented 4 years ago

Thanks for the insights! If I implement my own scope, wouldn't I still need to mention it with every single bind? I think it would be nice to "install" a replacement for the default deduction rules if the defaults are never compatible with the way I've structured my code. Is this possible?

It may also be worth noting that I'm using the injector module approach. So, it seems odd to me that the producer of an injector would have to anticipate the way client code will request types (eg, via const T& or std::unique_ptr). Would it be possible for the user of an injector to specify the scopes and/or deduction rules to be used?

kanstantsin-chernik commented 4 years ago

If I implement my own scope, wouldn't I still need to mention it with every single bind?

Not if you will implement config with type traits

Would it be possible for the user of an injector to specify the scopes and/or deduction rules to be used?

You can use both approaches. You can ether enforce scope by in or just left is for consumer deduction. I personally think that consumer shouldn't be responsible for lifetime of consumed objects but it is a matter of opinion