AliSoftware/Dip

Make Auto Injection Optional

mohamede1945 opened this issue · 3 comments

Because of the current implementation of Auto-injection I think we should provide a way to turn it off. It is implemented by going through all properties of each object being created including super class ones because of that big projects with large number of dependencies and objects with many properties tend to take time to resolve such object graphs because of auto-injection overhead.

I would suggest you can have a way to completely turn it off like:

let container = DependencyContainer(autoInjectionEnabledByDefault: false)

Users can still override the default behavior for individual registrations.

container.register(.unique, autoInjectionEnabled: .enabled) { Client() }

Edit:
The initializer would default to true

class DependencyContainer {
    init(autoInjectionEnabledByDefault: Bool = true) { }
}

And the register would use an enum, defaulting to useDefault:

enum AutoInjectionEnabled {
  case useDefault
  case enabled
  case disabled
}

func register<T>(_ scope: ComponentScope = .shared, type: T.Type = T.self, tag: DependencyTagConvertible? = nil, autoInjectionEnabled: AutoInjectionEnabled = .useDefault, factory: @escaping (()) throws -> T) -> Definition<T, ()> {
    let definition = DefinitionBuilder<T, ()>

@mohamede1945 that's a good point, but this will be a breaking change for current behavior, so I'd say the default should be true.

@mohamede1945 There is now a parameter in container configuration and a method to override it on a single definition, i.e.:

let container = DependencyContainer(autoInjectProperties: false)
container.register { ServerImp() as Server }
container.register { ClientImp() as Client }
  .autoInjectingProperties(true)

That's perfect. Thanks for implementing it.