How to use auto-wiring mocks in Spring for Delphi?

If I have these interfaces:

ISequencer = interface;
IController = interface;

      

Implementation for these (controller requires sequencer by constructor 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, using the auto-posting function, I can get a new instance of the interface IController

:

Controller := ServiceLocator.GetService<IController>;

      

This is normal for real application code. But in a test project I want to make fun of ISequencer

. Depending on the test, when I ask the container to implement for ISequencer

, sometimes I need a real implementation ( TSequencer

) and other times I need a mock implementation (for example TSequencerMock

). How can I make this switch?

+3


source to share


1 answer


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

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

      

And then you can call them by name:



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

      

I wrote an article on how to do this:

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

+4


source







All Articles