2016-10-31 33 views
1

当项目使用服务定位器时,实现类将在定位器中注册。然后在某些地方运行时定位器被要求解决某些服务是这样的(很多这些服务都是单身):服务位置 - 检查项目的实现

LSvc := Locator.Resolve<ISomeService>; 

坏的事情是,它是一种反模式。但是,假设这是事实,有没有办法通过在locator中注册这个类来检查是否有一个实现ISomeService的单元?

Locator.Register<ISomeService>(TSomeService); 
  1. 解析的源文件;
  2. 拥有名为“* .Dependencies.pas”的特殊单位,其中列出了所有执行单元。

在这种情况下还能做什么?

回答

0

有可能使用RTTI信息找到它。所以下面的代码只适用于最新版本的Delphi。

var 
    LIntf, LClass: TRttiType; 
    LImpl: TRttiInterfaceType; 
    LCtx: TRttiContext; 
    LFound: Boolean; 
begin 
    LCtx := TRttiContext.Create; 
    for LIntf in LCtx.GetTypes do 
    if LIntf.TypeKind = tkInterface then 
     begin 
     LFound := False; 
     for LClass in LCtx.GetTypes do 
      begin 
      if LClass.TypeKind = tkClass then 
       for LImpl in TRttiInstanceType(LClass).GetImplementedInterfaces do 
       if LImpl.QualifiedName = LIntf.QualifiedName then 
        begin 
        LFound := True; 
        Break; 
        end; 

      if LFound then 
       Break; 
      end; 

     if not LFound then 
      Writeln(LIntf.QualifiedName, ' is not implemented by any class.'); 
     end; 
end; 

您可以通过QualifiedName过滤接口和类型。该名称包含完整的单元名称作为该类型的前缀。

因此,即使没有应用过滤器,也可以将其输出保存到文本文件,并在过滤掉不需要的(不需要的接口)之后,您将能够找到在项目中编译的接口,但在那里没有实现它们的类。

当服务在项目之间重复使用并通过服务定位器请求时,情况就是如此。