Pergunta

If I have these interfaces:

ISequencer = interface;
IController = interface;

The implementation for them (Controller requires Sequencer by contructor injection):

TSequencer = class(TInterfacedObject, ISequencer)
end;

TController = class(TInterfacedObject, IController)
  constructor Create(Sequencer: ISequencer);
end;

I register the implementations in the global container:

GlobalContainer.RegisterType<TSequencer>.Implements<ISequencer>;
GlobalContainer.RegisterType<TController>.Implements<IController>;

GlobalContainer.Build;

And finally, with the auto-wiring feature I can get a new instance of the IController interface:

Controller := ServiceLocator.GetService<IController>;

That's ok for the real application code. But in the test project I want to mock ISequencer. Depending on the test, when I ask the container for an implementation for ISequencer, sometimes I need the real implementation (TSequencer) and other times I need a mock implementation (like TSequencerMock). How can I do this switch?

Foi útil?

Solução

You can register more than one implementation for a given interface. You then call them by name:

GlobalContainer.RegisterType<TSequencer>.Implements<ISequencer>('real');
GlobalContainer.RegisterType<TController>.Implements<IController>('mock');

And then you can call them by name as desired:

Controller := ServiceLocator.GetService<IController>('mock');

I wrote an article about how to do it here:

http://www.nickhodges.com/post/Getting-Giddy-with-Dependency-Injection-and-Delphi-Spring-9-%E2%80%93-One-Interface-Many-Implementations.aspx

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top