How to avoid Dependency Injection constructor madness?

前端 未结 9 1824
别跟我提以往
别跟我提以往 2020-11-22 03:59

I find that my constructors are starting to look like this:

public MyClass(Container con, SomeClass1 obj1, SomeClass2, obj2.... )

with ever

9条回答
  •  抹茶落季
    2020-11-22 04:31

    I read this whole thread, twice, and I think people are responding by what they know, not by what is asked.

    JP's original question looks like he's constructing objects by sending a resolver, and then a bunch of classes, but we're assuming that those classes/objects are themselves services, ripe for injection. What if they are not?

    JP, if you're looking to leverage DI and desire the glory of mixing injection with contextual data, none of these patterns (or supposed "anti-patterns") specifically address that. It actually boils down to using a package which will support you in such an endeavor.

    Container.GetSevice(someObject1, someObject2)
    

    ... this format is rarely supported. I believe the difficulty of programming such support, added to the miserable performance that would be associated with the implementation, makes it unattractive for opensource developers.

    But it should be done, because I should be able to create and register a factory for MyClass'es, and that factory should be able to receive data/input that aren't pushed into being a "service" just for the sake of passing data. If "anti-pattern" is about negative consequences, then forcing the existence of artificial service types for passing data/models is certainly negative (on par with your feeling about wrapping up your classes into a container. Same instinct applies).

    There are framework that may help, though, even if they look a bit ugly. For example, Ninject:

    Creating an instance using Ninject with additional parameters in the constructor

    That's for .NET, is popular, and is still nowhere as clean as it should be, but I'm sure there's something in whatever language you choose to employ.

提交回复
热议问题