injector icon indicating copy to clipboard operation
injector copied to clipboard

Configure injector to ignore constructor parameters of certain types

Open mwgamble opened this issue 6 years ago • 4 comments
trafficstars

I'd like to configure Injector to ignore all constructor parameters that are typed with str, int or bool. Is this possible? Right now I have to leave off the type declarations for these parameters, even if they also have a default value. If I don't, it will pass through an empty string for str parameters (not sure about other types).

mwgamble avatar Mar 08 '19 04:03 mwgamble

You can either disable auto_bind Injector-wide (it won't provide types you didn't explicitly bind to implementations) or use noninjectable (https://injector.readthedocs.io/en/latest/api.html#injector.noninjectable) in those cases.

jstasiak avatar Mar 08 '19 10:03 jstasiak

Hang on, but how are you constructing those types that have constructors with str-typed parameters anyway? Either you construct them yourself, and then Injector won't provide anything, or you use AssistedBuilder and Injector will let you fill in the blanks. Can you provide some code?

jstasiak avatar Mar 08 '19 10:03 jstasiak

noninjectable is exactly what I was looking for. Thank you so much!

Using auto_bind wasn't practical in the project I'm working in. I don't recall exactly why now, but I have a feeling it was because it would attempt to auto-bind all classes (including in third-party packages), rather than just non-vendor code. As we still wanted to separate out the DI config from the rest of the codebase, we ended up overriding Injector.create_object() and performing auto-binding there, but only for classes in our own project. This ended up also being the correct place to use noninjectable.

Either you construct them yourself, and then Injector won't provide anything

If I create an instance of this class using Injector.create_object(), then self.param1 ends up as an empty string, rather than the default value specified in the signature.

from injector import Injector

class MyClass(object):
    def __init__(self, param1: str = 'test'):
        self.param1 = param

di = Injector(auto_bind=True)
myobj = di.create_object(MyClass)
print(myobj.param1) # prints '', not 'test'

mwgamble avatar Mar 12 '19 03:03 mwgamble

Oh, I see - I'm glad that noninjectable is helpful here, you're welcome.

jstasiak avatar Mar 12 '19 06:03 jstasiak