datasnap——动态注册服务类
datasnap——动态注册服务类
在DataSnap的应用程序时,我们首先需要注册的服务器类,以提供访问客户端应用程序的服务器方法。通常的做法是使用DSServerClass组件,但有些时候,我们要做到在运行时加载。下面代码实现的类TSimpleServerClass从TDSServerClass继承,超载了Create方法并且增加了ServerClass,DataSnap Server和LifeCycle三个参数。
type
TSimpleServerClass = class(TDSServerClass)
private
FPersistentClass: TPersistentClass;
protected
function GetDSClass: TDSClass; override;
public
constructor Create(AOwner: TComponent; AServer: TDSCustomServer;
AClass: TPersistentClass; ALifeCycle: String); reintroduce; overload;
end;
procedure RegisterServerClasses(AOwner: TComponent; AServer: TDSServer);
implementation
constructor TSimpleServerClass.Create(AOwner: TComponent; AServer: TDSCustomServer;
AClass: TPersistentClass; ALifeCycle: String);
begin
inherited Create(AOwner);
FPersistentClass := AClass;
Self.Server := AServer;
Self.LifeCycle := ALifeCycle;
end;
function TSimpleServerClass.GetDSClass: TDSClass;
begin
Result := TDSClass.Create(FPersistentClass, False);
end;
现在我们只需要为每个Server Class初始化TSimpleServerClass。下面的代码在同一服务器上注册3个不同生命周期的类。
procedure RegisterServerClasses(AOwner: TComponent; AServer: TDSServer);
begin
Assert(AServer.Started = false, 'Can''t add class to non active Server');
TSimpleServerClass.Create(AOwner, AServer, TGlobal, TDSLifeCycle.Server);
TSimpleServerClass.Create(AOwner, AServer, TCustomer, TDSLifeCycle.Session);
TSimpleServerClass.Create(AOwner, AServer, TObjectPool, TDSLifeCycle.Invocation);
end;