Search code examples
delphidependency-injectionfactoryspring4d

Spring4d - Automatic factory with service name


I am trying to use the automatic virtual factory functionality of Spring4d. Though, I would like to be able to pass the ServiceName I want to resolve inside the factory Build() function. Like so : AFactory.Build(AServiceName)

For example

TMyComponent1 = class(TInterfacedObject, IMyService)
public
  constructor Create(AArgument : TObject);
end;

TMyComponent2 = class(TInterfacedObject, IMyService)
public
  constructor Create(AArgument : TObject);
end;

TMyComponent3 = class(TInterfacedObject, IMyService)
public
  constructor Create(AArgument : TObject);
end;

// Registering components

AContainer.RegisterType<TMyComponent1, IMyService>('Service1');
AContainer.RegisterType<TMyComponent2, IMyService>('Service2');
AContainer.RegisterType<TMyComponent3, IMyService>('Service3');

// Factory interface

IMyFactory = class(IInvokable)
[Guid]
  function Build(AArgument : TObject; AServiceName : string) : IMyService;
end;

// Factory registration

AContainer.RegisterType<IMyFactory>.AsFactory(); 

// Use factory

AContainer.Resolve<IMyFactory>(AObject, 'Service1'); // Should resolve TMyComponent1

I would like the factory to resolve the TMyComponent1 when AServiceName = 'Service1', TMyComponent2 when AServiceName = 'Service2', etc.

How can I acheive this?


Solution

  • You currently can't. Parameters all go through to the resolver being used as potential constructor parameters.

    It might be worth a feature request to be able to annotate a parameter of the factory interface to use that as the requested service type.

    However this will not be implemented any time soon as for 1.3 I have some changes to the system planned which will make contextual injection and registration possible. This will then possibly enable not only to determine the resolved service by its name but by any possible meta information provided.