AliSoftware / Dip

Simple Swift Dependency container. Use protocols to resolve your dependencies and avoid singletons / sharedInstances!
MIT License
978 stars 75 forks source link

Make Auto Injection Optional #212

Closed mohamede1945 closed 5 years ago

mohamede1945 commented 5 years ago

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, ()>
ilyapuchka commented 5 years ago

@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.

ilyapuchka commented 5 years ago

@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)
mohamede1945 commented 5 years ago

That's perfect. Thanks for implementing it.