GlobalContainer.ResolveAll / ServiceLocator.GetAllServices servers not the last registered service

Issue #21 resolved
Former user created an issue

With the ResolveAll and GetAllServices Calls in Release 1.0 I get only n-1 Services (XE3):

uses
  System.SysUtils,
  Spring.container;

type
  IFoo = interface
  ['{76FEA04B-5EFA-450A-88A5-AE92C89A05D1}']
  end;
  TBar1 = class(TInterfacedObject, IFoo)
  end;
  TBar2 = class(TInterfacedObject, IFoo)
  end;
  TBar3 = class(TInterfacedObject, IFoo)
  end;

var
  Foo: IFoo;
begin
  GlobalContainer.RegisterType<TBar1>.Implements<IFoo>;
  GlobalContainer.RegisterType<TBar2>.Implements<IFoo>;
  GlobalContainer.RegisterType<TBar3>.Implements<IFoo>;

  GlobalContainer.Build;

  for Foo in GlobalContainer.ResolveAll<IFoo> do
  begin
    writeln((Foo as TObject).ClassName);
  end;

  readln;
end.

It lists only TBar1 and TBar2.

Comments (3)

  1. Stefan Glienke repo owner

    This is by design.

    ResolveAll does not return the unnamed default service. Default registration is the registration without a name. If you have multiple registrations without a name always the last one is the default. In your case the default for IFoo is the one with TBar3.

    If you want ResolveAll to return all three you have to name them. However then you don't have a default (one that gets returned for IFoo dependencies or when you call Resolve) - you need to call .AsDefault on that one.

    Like this:

      container.RegisterType<TBar1>.Implements<IFoo>('foo1');
      container.RegisterType<TBar2>.Implements<IFoo>('foo2');
      container.RegisterType<TBar3>.Implements<IFoo>('foo3').AsDefault;
    

    I actually was thinking about only allowing one unnamed registration and throw an exception if you register another one without a name but did not do that - I might change that in the future.

  2. Stefan Glienke repo owner

    This issue has been handled by the recent change to TComponentRegistry.FindAll(serviceType: PTypeInfo) which is used by ResolveAll. It now only returns named registrations.

  3. Log in to comment