I’m just getting started with the Delphi Spring Framework and was wondering whether the current version of the DI container somehow allows delegating the construction to a factory method without specifying an implementing type?
E.g. something similar to this:
GlobalContainer
.RegisterFactory<ISomeObject>(
function: ISomeObject
begin
Result := CreateComObject(CLASS_SomeObject) as ISomeObject;
end)
.Implements<ISomeObject> // could probably be implied from the above
.AsSingletonPerThread;
As you can see, my specific use case is the instantiation of COM objects. In that case the class implementing the interface I’m interested in is not part of my application but I am still able to create instances by calling CreateComObject / CoCreateInstance. However, it seems I’m out of luck as registrations in the Container always appear to be bound to an actual implementing class.
Assuming this isn’t possible as such at the moment, how would you experts out there address this? Would you create a wrapper class or dummy class or would you simply keep COM objects out of the DI container and simply instantiate them via CreateComObject?
Unfortunately the current design of the spring DI container does not allow that. It internally assumes that every service type (usually interface, but can also be a class) is implemented by a component type (a class). Thus having
TObjectat several places where we would needIInterfacein this case. Like the delegate you are passing to the DelegateTo method returns the component type (or TObject in the non generic case) and not the service type.That is also because you can register one component type with multiple interface implementations in just one fluent interface call. Like:
The container now checks if
TMyObjectis compatible toIMyInterfaceandIMyOtherInterface. When callingResolvethe service resolver usesGetInterfaceon the instance to get the requested interface reference. Everything beyond that point is done on an object reference.Since I have some plans for the DI container that require not having a dependency on an implementing class when registering interfaces this issue will be addressed in the future but not anytime soon.
Update (08.11.2012):
Since r522 it is possible to register interface types in the following way:
In this example it will register
ISomeObjectas service and any interface with a GUID it inherits from.Additionally you can add other interfaces by calling
Implements<T>but unlike for classes there will be no validation at registration time if the constructed instance actually really supports that interface since it simply is not possible. Currently you will getnilwhen callingResolve<T>with a non supported service type. It may raise an exception in the future.