Question

Using the Delphi Spring framework, is it possible to register a generic type with the GlobalContainter? I'm trying to do something like this:

TMyBaseType = class
protected
  FName: string;
  function GetName: string; virtual;
  procedure SetName(Value: string); virtual;
public
  property Name: string read GetName write SetName;
end;

TMyFirstThing = class(TMyBaseType)
protected
  function GetName: string; override;
end;

TMySecondThing = class(TMyBaseType)
protected
  procedure SetName(Value: string); override;
end;

TMyGenericType<T: TMyBaseType> = class
public
  procedure DoSomethingWithIt(AObject: T);
  function GetTheSomethingsName(AObject: T): string;
end;

// I now want to be able to use the ServiceLocator to get me an instance
// such as TMyGenericType<TMyFirstThing> or TMyGenericType<TMySecondThing>
// but I cannot figure out how to register TMyGenericType<>

......

initialization
  GlobalContainer.RegisterType<TMyGenericType<>>;
// this line fails with the messages:
// [DCC Error] E2251 Ambiguous overloaded call to 'RegisterType'
// [DCC Error] E2531 Method 'RegisterType' requires explicit type argument(s)

I'm not sure if what I'm trying to do is possible or if there's a better/alternative way to do it? I'm using Delphi 2010 with the latest Spring4D framework. (I also have Delphi XE5 but the project itself is still 2010 due to 3rd party libraries). Any ideas or suggestions would be most appreciated.

Was it helpful?

Solution

Delphi does not have unbound (or open) generic types (something like TMyGenericType<>.

In your case you have to register every closed constructed generic type (TMyGenericType<TMyFirstThing>, TMyGenericType<TMySecondThing>, ...) individually.

More informations about the differences of generics in C#, C++ and Delphi: http://blogs.teamb.com/craigstuntz/2009/10/01/38465/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top