Spring4D IoC and specific singleton

Spring4D IoC and specific singleton

I have a generic interface to write data to the database: IDBStorer. This interface can write data to any pre-defined table (generates inserts and updates). I would like the group of objects that saves, for example, orders, to use one instance of this interface, but configured to store orders. Completely in other place, another group of objects saves, for example, car routes, also uses the IDBStorer interface, but with a completely different configuration.

Therefore, I would need to resolve the interface from the factory using some type of "order" or "route" and to get the same instance for each "route" request, but different than when I resolve for "order".

Something like this:

OrdersStorer := Container.Resolve.NamedSingleton('orders');
RouteStorer := Container.Resolve.NamedSingleton('route');

or better by factory:

TStorerFactory = reference to function(aStorerIdentifier : string) : IDBStorer;
Container.RegisterFactory.AsNamedSingleton;

OrderStorer := StorerFactory('orders');
OrderStorer2 := StorerFactory('orders');
RouteStorer := StorerFactory('route');

and I get one instance IDBStorer per unique string, so OrderStorer is equal in this case OrderStorer2 (because resolved by this same unique identifier 'orders')

Is it possible?

Comments

  1. A. Bouchez Singleton in DI means not the same as in the design pattern. It means that it is ensured that there is only one instance every time I ask for this as a dependency but not a new instance each time. And the subtle but important difference is that the singletoness is not baked into the class itself but controlled by the container and how you configure things.

    ReplyDelete
  2. Stefan Glienke You are right. I remember now - I already made this confusion some time ago... same naming is IMHO wrong. "Shared" or "Common" could be less confusing for sure. In our framework we use "sicShared" for such an instance livetime.

    ReplyDelete
  3. A. Bouchez I did not invent the naming but it is called like that in most DI frameworks. Being really pedantic though I would say that it is an implementation detail of the pattern that is the bad thing and when you do DI the implementation of it is good as it is not coupled to the core responsibility of the class and not part of the class itself but of the mechanism that creates them.

    ReplyDelete

Post a Comment