Typed interfaces and Spring4D - delphi

I am trying to use typed interfaces and Spring4D, but have some issues with Resolving. Please review details below.
DB Objects:
unit u_DB;
type
TDBObject = class
public
property ID: TGUID;
end;
TDBCRM = class(TDBObject)
public
property SOME_FIELD: TSomeType;
end;
Declarations:
unit i_BaseDAL;
type
{$M+}
IBaseDAL<T: TDBObject, constructor> = interface
['{56D48844-BD7F-4FF8-A4AE-30DA1A82AD67}']
procedure RefreshData();
....
end;
unit u_BaseDAL;
type
TBaseDAL<T: TDBObject, constructor> = class(TInterfacedObject, IBaseDAL<TDBObject>)
public
procedure RefreshData();
....
end;
After that I was able to register the base IBaseDAL and IBaseDAL
GlobalContainer.RegisterType<IBaseDAL<TDBObject>>;
GlobalContainer.RegisterType<IBaseDAL<TDBCRM>>;
Using in project:
I need to resolve now IBaseDAL, but could not find how do it. Only below ugly approach work
DM := GlobalContainer.Resolve('i_BaseDAL.IBaseDAL<u_DB.TDBObject>#TBaseDAL<u_DBCRM.TDBCRM>').AsInterface as IBaseDAL<TDBObject>;
but I was hoping that below will work :) -
DM := GlobalContainer.Resolve(IBaseDAL<TDBCRM>);
Please advise how could it be resolved correctly?

Edit: I just noticed that somehow the interface table does not contain generic interfaces so you have to explicitly register them as explained below.
First you need to register an implementation and not just an interface.
GlobalContainer.RegisterType<TBaseDAL<TDBObject>>;
GlobalContainer.RegisterType<TBaseDAL<TDBCRM>>;
GlobalContainer.Build;
The container will inspect the class you registered and register all implemented interfaces (except IInterface) so it will know about IBaseDAL<TDBObject> and IBaseDAL<TDBCRM>.
If your class might implement some interfaces you don't want the container to know you have to register explicit:
GlobalContainer.RegisterType<IBaseDAL<TDBObject>, TBaseDAL<TDBObject>>;
GlobalContainer.RegisterType<IBaseDAL<TDBCRM>, TBaseDAL<TDBCRM>>;
GlobalContainer.Build;
Then you can resolve:
GlobalContainer.Resolve<IBaseDAL<TDBCRM>>;
By the way, are you sure your class definition should not be as follows?
type
TBaseDAL<T: TDBObject, constructor> = class(TInterfacedObject, IBaseDAL<T>)

Related

How use multi interface class in Spring4D

I'm just learning Spring4D and i have one question.
If class implement only one interface its all clear:
IWeapon = interface
['{E679EDA6-5D43-44AD-8F96-3B5BD43A147B}']
procedure Attack;
end;
TSword = class(TInterfacedObject, IWeapon)
public
procedure Attack;
end;
GlobalContainer.RegisterType<TSword>.Implements<IWeapon>('sword');
sword := ServiceLocator.GetService<IWeapon>('sword');
and im really happy now, I have sword and i dont need to Free it.
but if class implements two or more interfaces:
IWeapon = interface
['{E679EDA6-5D43-44AD-8F96-3B5BD43A147B}']
procedure Attack;
end;
IShield = interface
['{B2B2F443-85FE-489C-BAF4-538BB5B377B3}']
function Block: Integer;
end;
TSpikedShield = class(TInterfacedObject, IWeapon, IShield)
public
function Block: Integer;
procedure Attack;
end;
GlobalContainer.RegisterType<TSpikedShield>.Implements<IWeapon>.Implements<IShield>;
I can ask ServiceLocator for an instance of TSpikedShield but i need choose one IWeapon or IShield. But I want use it in two ways(or i shouldn't want?) like:
spikedShield.Attack;
spikedShield.Block;
So if I good undestand, I have to create instance of TSpikedShiled directly(i mean without interface).
function MakeSpikedShield: TSpickedShield;
begin
result := TSpickedShield.Create;
end;
There is any way to use this class but with automagical Free?
(there won't be problem if interfaces could implement multi interfeces but its not allowed in delphi)
Edited:
maybe somethink like that?
ISpikedSield = interface
function AsWeapon: IWeapon;
function AsShield: IShield;
end;
TSpikedShield = class(TInterfacedObject, ISpikedShield)
There won't be problem if interfaces could implement multi interfaces but it's not allowed in Delphi
That is the exact cause of the problem.
I would just make an ISpikedShield interface that has the methods of IWeapon and IShield and making sure that every class that implements ISpikedShield also explicitly implements IWeapon and IShield (this is what the compiler basically does for you in C# for example where an interface can inherit from multiple other interfaces).
You then cannot assign an ISpikedShield to an IWeapon and IShield but using as operator will work because the class behind implements them.
However I am not sure if there is not a misconception in your architecture because if you think further there won't be a class that has an ISpikedShield as dependency but rather an IWeapon and/or IShield. Some game code would then check if your IShield supports ICanAttack to do an additional hit apart from those you can do with your IWeapon.

Must I define both the forward declaration and the interface of a class in the same section?

I have a class that I want to keep private, because I only use it in the implementation section.
However it is used by a class that is declared public in the interface section.
Is there a way to do something like this:
unit x;
interface
type
TPrivate = class; //forward declaration
TPublic = class(TSomething)
private
FPrivate: TPrivate;
procedure DoStuffWithFPrivate;
public
//...
end;
implementation
type
TPrivate = class(TObject)
procedure Test;
end;
Obviously the above code gives an error:
[dcc32 Error] UnitX.pas(27): E2086 Type 'TPrivate' is not yet completely defined
I don't want to resort to cheap tricks like:
FPrivate = TObject
....
procedure TPublic.DoStuffWithFPrivate;
begin
TPrivate(FPrivate).Test;
Is there a way to do what I want without having to spill TPrivate's internal details in the interface?
I know it's possible to declare TPrivate as a strict private sub type of TPublic, however I don't like the pollution of the interface section this gives.
Is there a way to keep TPrivate out the of interface section (as much as possible) whilst maintaining type safety?
As long as TPrivate is not used anywhere in the interface of TPublic besides the field declaration (f.i. as a methods parameter type) you can use a local class helper to achieve this.
Note: FPrivate is not a good name for that field!
interface
type
THiddenActual = class
end;
TPublic = class
private
FActual: THiddenActual;
procedure DoStuffWithFPrivate;
public
end;
implementation
type
TActual = class(THiddenActual)
public
procedure Foo;
end;
type
TPublicHelper = class helper for TPublic
private
function GetActual: TActual;
procedure SetActual(const Value: TActual);
public
property Actual: TActual read GetActual write SetActual;
end;
procedure TActual.Foo;
begin
end;
function TPublicHelper.GetActual: TActual;
begin
Result := FActual as TActual;
end;
procedure TPublicHelper.SetActual(const Value: TActual);
begin
FActual := Value;
end;
procedure TPublic.DoStuffWithFPrivate;
begin
Actual.Foo;
end;
OK, it is merely a little variance of that cheap trick, but what are the alternatives? You have to take what is available, don't you?
I'm not sure what exactly your definition of "pollution" is as regards the interface section, but if it's just a matter of keeping it from drowning your TPublic class definition with noise then one option might be simply inheritance :
TBasePublic = class(TSomething)
private
type
TPrivate = class
// ...
// ... keep TPrivate definition separate
end;
end;
TPublic = class(TBasePublic)
private
FPrivate : TPrivate;
end;
This would even allow you to define TPrivate in a completely different unit if segregation is your goal.

Interface inheritance without generics

I am trying to implement an interface to convert records in a dataset to Delphi records in a pre-generics version of Delphi. I don't like the interface at the moment, as it will always need calls to Supports which I'd like to avoid if possible and was wondering if there's a better way of doing it that I'm missing.
So far I have an navigation interface and data retrieval interface defined:
IBaseRecordCollection = interface
procedure First;
procedure Next;
function BOF: boolean;
... // other dataset nav stuff
end;
IRecARecordCollection = interface
function GetRec: TRecA;
end;
IRecBRecordCollection = interface
function GetRec: TRecB;
end;
Basically I have a concrete base class that contains a private dataset and implements IBaseRecordCollection and concrete class for each RecordCollection interface which derives from an abstract class implementing the IBaseRecordCollection (handled by an implements property) with the implementation of the record retrieval routine:
TAbstractTypedRecordCollection = class(TInterfacedObject, IBaseRecordCollection)
private
FCollection: IBaseRecordCollection;
protected
property Collection: IBaseRecordCollection read FCollection implements IBaseRecordCollection;
public
constructor Create(aRecordCollection: IBaseRecordCollection);
end;
TRec1RecordCollection = class(TAbstractTypedRecordCollection, IRecARecordCollection);
public
function GetRec: TRecA;
end;
Now, to use this I'm forced to have a builder that returns a IRecARecordCollection and then mess around with Supports, which I'm not keen on as it will always be used in this fashion.
i.e.
procedure GetMyRecASet;
var
lRecARecordCollection: IRecARecordCollection;
lRecordCollection: IBaseRecordCollection;
begin
lRecARecordCollection := BuildRecACollection;
if not supports(lRecARecordCollection, IBaseRecordCollection, lRecordCollection) then
raise exception.create();
while not lRecordCollection.EOF do
begin
lRecARecordCollection.GetRec.DoStuff;
lRecordCollection.Next;
end;
end;
Although this works, I'm not keen on the supports call and mixing my lRecordCollections and my lRecARecordCollections like this. I had originally hoped to be able to do something like:
IBaseRecordCollection = interface
// DBNav stuff
end;
IRecARecordCollection = interface (IBaseRecordCollection)
function GetRec: TRecA;
end;
TRec1RecordCollection = class(TInterfacedObject, IRecARecordCollection)
private
FCollection: IBaseRecordCollection;
protected
property Collection: IBaseRecordCollection read FCollection implements IBaseRecordCollection;
public
function GetRec: TRecA;
end;
but unfortunately Delphi wasn't smart enough to realise that the implementation of IRecARecordCollection was split over the base IBaseRecordCollection in the Collection property implements call and the TRec1RecordCollection object.
Are there any other suggestions for neater ways to acheive this?
-- edit to give a (longer) reply to #David's answer than possible in a comment
The suggested solution of:
IBaseRecordCollection = interface ['{C910BD0A-26F4-4682-BC82-605C4C8F9173}']
function GetRecNo: integer;
function GetRecCount: integer;
function GetFieldList: TFieldList;
function EOF: boolean;
function BOF: boolean;
...
end;
IRec1RecordCollection = interface (IBaseRecordCollection) ['{E12F9F6D-6D57-4C7D-AB87-8DD50D35DCA2}']
function GetRec: TRec1;
property Rec: TRec1 read GetRec;
end;
TAbstractTypedRecordCollection = class(TInterfacedObject, IBaseRecordCollection)
private
FCollection: IBaseRecordCollection;
protected
property Collection: IBaseRecordCollection read FCollection implements IBaseRecordCollection;
public
constructor Create(aRecordCollection: IBaseRecordCollection);
end;
TRec1RecordCollection = class(TAbstractTypedRecordCollection, IRec1RecordCollection, IBaseRecordCollection)
private
function GetRec: TRec1;
public
property Rec: TRec1 read GetRec;
end;
isn't compiling. It's complaining that TRec1RecordCollection cannot find methods related to IBaseRecordCollection. I also tried moving the Collection property from Abstract to Rec1RecordCollection and redeclaring the property in TRec1RecordCollection all with the same result
Looking a bit deeper it appears that direct inheritance of a class implementing IBaseRecordCollection would work but Delphi can't handle doing it indirectly via a property using implements.
Your code is almost there. The implements directive in your code fails to compile because you only declared that your class implements the derived interface. As it stands, your class does not implement the interface that the implements directive refers to, namely IBaseRecordCollection. You might think that would be inferred from the inheritance but it is not.
To solve your problem you simply need to declare that TRec1RecordCollection implements both interfaces:
type
TRec1RecordCollection = class(TInterfacedObject, IBaseRecordCollection,
IRecARecordCollection)
....
end;
Make just the one small change and your code will compile.
Update
Your edit to the question changes this somewhat. The code in my answer does indeed compile, given the code in your original question. However, add any method into IBaseRecordCollection and the compile will not accept it.
The compiler should accept this code and the fact that it does not is because of a compiler bug. Modern versions of Delphi will accept the code in your update to the question.
Unless you upgrade your compiler you will not be able to make your intended design work.

Testing a class not declared in the interface section

I'm a newbie with Dependency Injection containers, and I am trying to get my head around using them in conjunction with Mocking.
Lets say I have a controller and a list (the model):
IBlahList = interface
property Items[AIndex: integer]: IBlah read GetItem;
end;
IController = interface
property List: IBlahList read GetList;
end;
The implementation of IController would look something like (note, it's in the implementaion section:
implementation
TController = class (TInterfacedObject, IController)
private
FList: IBlahList;
function GetList: IBlahList;
public
constructor Create(const AList: IBlahList);
end;
And then, of course, I would register this class (as well as one for IBlahList) with the GlobalContainer:
GlobalContainer.RegisterType<TController>.Implements<IController>;
I place the TController in the implementation section, as suggested by various sources (well, Nick Hodges anyway!), so that we cannot reference the TController class directly.
Now, just say I want to test my implementation of ICollection in a unit test:
procedure TestSomething
var
LMockList: TMock<IBlahList>;
LController: IController;
begin
LMockList := TMock<IBlahList>.Create;
// Oops, I can't do this, I can't access TController
LController := TController.Create(LMockList);
end;
So, my question is, should I move the TController class into my interface section so I can test it, or is there some other way to pass the mock IBlahList to the controller that I have yet to find?
If you have the concrete class in the implementation section, then you could expose a factory function (i.e. have it in the interface section) that creates an IController with the required parameters.
It makes absolutely no sense to have an implementation that can not be instantiated, IMO.
interface
...
function CreateController(AList: IBlahList): IController;
implementation
function CreateController(AList: IBlahList): IController;
begin
Result := TController.Create(AList);
end;
Well you probably should be using the mock framework in your test projects as well, but in these cases I usually "cheat" and move the implementation to where I need it using a DUNIT conditional variable:
// In the real app, we want the implementation and uses clauses here.
{$IFNDEF DUNIT}
implementation
uses
classes;
{$ENDIF}
type
TClassUnderTest = class(TObject)
// ...
end;
// In test projects it is more convenient to have the implemenation and
// uses clauses down here.
{$IFDEF DUNIT}
implementation
uses
classes;
{$ENDIF}
Then make sure that any test projects define the DUNIT conditional var, and move any units needed by the TClassUnderTest declaration to the interface section. The latter you can do permanently or under control of the DUNIT conditional as well.
I can just say: don't listen to Nick in that case.
Putting a class inside the implementation part of a unit just has disadvantages and you are facing one of them.
The whole point of using dependency injection is to decouple pieces of your code.
Now you removed the static dependency of TController and some class that implements IBlahList but you pulled in another (and much worse imo) dependency: the dependency on the DI container.
Don't put the class inside the implementation part of a unit just to prevent someone from directly creating it in your production code. Also don't put in the dependency on the DI container into that unit.
A much better approach is to have 3 units: interface, class, registration.
Edit:
I suggest reading this article and pay attention to the underlined parts: http://www.loosecouplings.com/2011/01/dependency-injection-using-di-container.html
Edit2 - added some pseudo code to show what I mean.
The unit test code could exactly be as in the question.
unit Interfaces;
interface
type
IBlahList = interface
property Items[AIndex: integer]: IBlah read GetItem;
end;
IController = interface
property List: IBlahList read GetList;
end;
implementation
end.
-
unit Controller;
interface
uses
Classes,
Interfaces;
type
TController = class (TInterfacedObject, IController)
private
FList: IBlahList;
function GetList: IBlahList;
public
constructor Create(const AList: IBlahList);
end;
implementation
...
end.
-
unit Registration;
interface
implementation
uses
Interfaces,
Controller,
Spring.Container;
initialization
GlobalContainer.RegisterType<TController>.Implements<IController>;
end.

TGenericClass<T> containing a TObjectList<T> doesn't compile

I'm trying to write a generic class which contains a generic TObjectList< T > which should contain only Elements of TItem.
uses
Generics.Collections;
type
TItem = class
end;
TGenericClass<T: TItem> = class
public
SimpleList: TList<T>; // This compiles
ObjectList: TObjectList<T>; // This doesn't compile: Compiler complaints that "T is not a class type"
end;
Is this a wrong syntax? BTW: TGenericClass< T: class> compiles, but then the Items in the List are not TItem anymore which is what I don't want.
This is a known bug with the D2009 compiler. It will most likely be fixed soon, either in an update or hotfix for 2009, or in Delphi 2010 (Weaver) once it gets released. Until then, you need some sort of workaround, unfortunately. :(
Generic types can have several constraints:
A class name, the generic type must be of that class of a descendant of the class.
An interface name, the generic type must implement that interface.
'class', the generic type must be a class (this can't be combined with a classname).
'record', the generic type must be a record.
'constructor', a bit vague, but you can create instances of the generic class type.
If you create a generic that uses other generics, you need to copy the constraints, else it won't work. In your case, TObjectList has the class constraint. This means, your T needs that constraint too.
Unfortunately this can't be combined with the named class constraint.
So I advice you to use an interface, these can be combined:
type
IItem = interface end;
TItem = class (TInterfacedObject, IItem) end;
TGenericClass<T: class, IItem> = class
private
FSimpleList: TList<T>;
FObjectList: TObjectList<T>;
end;
Besides, you should make your fields private else anyone can change them.
I like GameCat's answer (gave it +1) for the description of class constraints.
I have a slight modification of your code that works. Note that since you gave a constraint to say that T must be a descendant of TItem, you can actually just declare ObjectList as TObjectList<TItem> - no need to use T here.
Alternatively, you could create a proxy of sorts. First, note GameCat's comment about fields being private.
type
TGenericClass<T: TItem> = class
private
type
D = class(TItem); // Proxy to get your T into and object list
private
SimpleList: TList<T>;
ObjectList: TObjectList<D>; // Compiles now, but there is that type issue
public
procedure Add(Item: T); // No direct access to ObjectList
end;
Add is an example of how to access the object list. As it turns out, you can pass Item to ObjectList.Add with no trouble whatsoever:
procedure TGenericClass<T>.Add(Item: T);
begin
ObjectList.Add(Item);
end;
I think that may be a bug though, so to protect yourself against that getting fixed:
procedure TGenericClass<T>.Add(Item: T);
var
Obj: TObject;
begin
Obj := Item;
ObjectList.Add(D(Obj));
end;
Given your scenario though, I'd say TObjectList should do just fine.

Resources