ybainier / Hypodermic

Hypodermic is an IoC container for C++. It provides dependency injection to your existing design.
MIT License
575 stars 81 forks source link

Alternatives to `std::make_shared` #58

Open DeveloperPaul123 opened 1 year ago

DeveloperPaul123 commented 1 year ago

Would it be possible to add the ability to create instances with something other than std::make_shared. Some of our objects require a custom deleter and it seems that we cannot inject the deleter when registering types.

Is there a way to accomplish this now by inheriting from a container builder?

judgeaxl commented 1 year ago

What you would do is to register a factory that returns the pointer initialized the way you want it to be using builder.registerInstanceFactory. There's an example on the wiki: https://github.com/ybainier/Hypodermic/wiki/Registering-components#register-a-factory

DeveloperPaul123 commented 1 year ago

We're aware of this feature, but it forces us to have to explicitly pass all the necessary parameters to the type (via context.resolve<>) when constructing it.

Is there a way to instead change the default to something else other than std::make_shared and benefit from the auto-wiring and just use registerType()?

judgeaxl commented 1 year ago

I see what you're getting at. I imagine it would be possible to add something like a .withDeleter(x) when registering a type. That feels like the best fit to the existing API instead of replacing std::make_shared wholesale. However, I'm not a maintainer and while I have dug very deep into this library for various reasons, I think it would probably take a bit of work to add it.

judgeaxl commented 1 year ago

Actually, I looked back at the logic for resolving arguments automatically, and you'd have to provide both the deleter, and allocator, or a method that does both, so just .withDeleter would not work.