Delphi Spring DI: Is it possible to delegate interface instantiation without an implementing type?

后端 未结 2 760
面向向阳花
面向向阳花 2021-02-09 06:04

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 fact

2条回答
  •  滥情空心
    2021-02-09 07:06

    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 TObject at several places where we would need IInterface in 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:

    GlobalContainer
      .RegisterType
      .Implements
      .Implements;
    

    The container now checks if TMyObject is compatible to IMyInterface and IMyOtherInterface. When calling Resolve the service resolver uses GetInterface on 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:

    GlobalContainer
      .RegisterType
      .DelegateTo(
        function: ISomeObject 
        begin 
          Result := CreateComObject(CLASS_SomeObject) as ISomeObject; 
        end)
      .AsSingletonPerThread;
    

    In this example it will register ISomeObject as service and any interface with a GUID it inherits from.

    Additionally you can add other interfaces by calling Implements 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 get nil when calling Resolve with a non supported service type. It may raise an exception in the future.

提交回复
热议问题