创建Delphi IoC.如何禁用Delphi的链接器删除未使用的类
发布时间:2020-12-15 09:51:28 所属栏目:大数据 来源:网络整理
导读:我在delphi中创建了一个IoC,能够自动注册任何具有IocSingletonAttribute的类. AutoRegister如下所示. procedure TIocContainer.AutoRegister;var ctx: TRttiContext; rType: TRttiType; attr: TCustomAttribute; Type: PTypeInfo;begin ctx := TRttiContext.
我在delphi中创建了一个IoC,能够自动注册任何具有IocSingletonAttribute的类.
AutoRegister如下所示. procedure TIocContainer.AutoRegister; var ctx: TRttiContext; rType: TRttiType; attr: TCustomAttribute; &Type: PTypeInfo; begin ctx := TRttiContext.Create; for rType in ctx.GetTypes do Begin for attr in rType.GetAttributes do Begin if TypeInfo(IocSingletonAttribute) = attr.ClassInfo then Begin &Type := IocSingletonAttribute(attr).&Type; RegisterType(&Type,rType.Handle,True); End; End; End; end; 然后我创建一个实现并将IocSingletonAttribute添加到它.看起来像这样 [IocSingleton(TypeInfo(IIocSingleton))] TIocSingleton = class(TInterfacedObject,IIocSingleton) procedure DoSomeWork; end; 所以,现在到程序的实际代码.如果我写下面的代码,IoC不起作用. AutoRegister过程没有选择TIocSingleton. var Ioc: TIocContainer; Singleton: IIocSingleton; begin Ioc := TIocContainer.Create; try Ioc.AutoRegister; Singleton := Ioc.Resolve<IIocSingleton>(); Singleton.DoSomeWork; finally Ioc.Free; end; end. 但是,如果我编写下面的代码,一切都按预期工作.请注意我是如何声明TIocSingleton类并使用它的. var Ioc: TIocContainer; Singleton: IIocSingleton; ASingleton: TIocSingleton; begin Ioc := TIocContainer.Create; ASingleton := TIocSingleton.Create; try Ioc.AutoRegister; Singleton := Ioc.Resolve<IIocSingleton>(); Singleton.DoSomeWork; finally Singleton.Free; Ioc.Free; end; end. 基于此,我假设Delphi的编译器链接器在第一个示例中删除了TIocSingleton,因为它从未在应用程序的任何部分中明确使用.所以我的问题是,是否可以为某个类转换编译器的“删除未使用的代码”功能?或者,如果我的问题不是链接器,任何人都可以阐明为什么第二个例子有效而不是第一个? 解决方法
将{$STRONGLINKTYPES ON}指令添加到.dpr.然后应该包括那些类型.但它肯定会炸毁您的应用程序,因为它不适用于单个类.
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |