AliSoftware / Dip

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

Singleton objects created multiple times #210

Closed mohamede1945 closed 5 years ago

mohamede1945 commented 5 years ago

This is a followup to #160

I think the problem here is the understanding of resolvingProperties. I think it should be named immediatelyResolvingProperties because it runs immediately after the object creation. Instead, we could have another kind of resolvingProperties which we might call it deferredResolvingProperties which would be called after creating the entire object graph.

So if I'm creating the relationship manually without any IoC containers I would do.

let client = Client()
let server = Server(client)
client.server = client

So I think the solution to this problem is to store deferredResolvingProperties somewhere until the entire object graph is created and then execute it. This way, we won't create multiple instances of singletons.

ilyapuchka commented 5 years ago

@mohamede1945 the singleton scopes insure not how many instances will be created at runtime, but only how many different references there will be in the object graph. You should't rely on initialiser being called multiple times or should better ensure that there are no circular dependencies.

mohamede1945 commented 5 years ago

The singleton scopes insure not how many instances will be created at runtime, but only how many different references there will be in the object graph.

I don't think this is correct. Singleton here means one instance across multiple object graphs within the same context (i.e. DependencyContainer). You're explaining shared not singleton.

If one container creates multiple instances of the same object (though it uses only the last). The semantic meaning of singleton scope is lost. It should be named something else to justify that instance can be created multiple times but only the last one will be used.

I don't know how you don't consider this is a bug. I'm sure there are many people using the library who won't understand that singleton means created multiple times and last one used across all different object graphs within the same container.

Anyway, we are not using this library anymore because of this problem and created our own to solve it. But wanted to share our idea with the community.

ilyapuchka commented 5 years ago

I'm glad you found a solution that works for you