简体   繁体   English

通过反射加载的DLL是否被缓存?

[英]Are DLLs loaded by reflection being cached?

I have an application that loads Type by reflection upon need since implementation may be changed by configuration. 我有一个应用程序可以根据需要通过反射加载Type,因为实现可能会因配置而改变。 here is a sample code: 这是一个示例代码:

var myObject = Activator.CreateInstance(Type.GetType("MyAssembly.MyClass, MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=1r46a5dfa04dase2"))as IMyClass

My Question here, is this Type being cached by default or it will be reloaded every time, and if not, How can I cache it to enhance performance? 我的问题是,此类型是默认缓存还是每次都会重新加载,如果没有,如何缓存它以提高性能?

Unlike instances, single types and their containing assemblys are,once used, not unloaded (assuming only one AppDomain), so basically the answer is yes, there is a cache. 与实例不同,单一类型及其包含的程序集是一次使用的,不会被卸载(假设仅一个AppDomain),因此基本上答案是肯定的,有一个缓存。

Also have a look here: Can you remove an Add-ed Type in PowerShell again? 还可以在这里查看:是否可以再次在PowerShell中删除添加类型?

Once loaded an assembly can't be unloaded (unless you unload the full AppDomain that loaded it) (see for example How to unload an assembly from the primary AppDomain? ). 加载后,无法卸载程序集(除非您卸载已加载程序集的完整AppDomain)(例如,请参见例如如何从主AppDomain卸载程序集? )。 So there is the opposite problem of yours :-) 因此,您遇到了相反的问题:-)

Now... You can surely speed up everything: 现在...您肯定可以加快一切:

Type myType = Type.GetType("MyAssembly.MyClass, MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=1r46a5dfa04dase2");

This call will need to be executed every time. 每次都需要执行此调用。 While the assembly won't be loaded, a search in the assembly will be done. 在不加载程序集的情况下,将在程序集中进行搜索。 You can cache myType . 您可以缓存myType

var myObject = Activator.CreateInstance(myType) as IMyClass;

This will search for a parameterless constructor for myType every time. 每次都会搜索myType的无参数构造函数。 You could speed up this by caching the constructor ( myConstructor ) you need: 您可以通过缓存所需的构造函数( myConstructor )来加快速度:

ConstructorInfo myConstructor = myType.GetConstructor(Type.EmptyTypes);

var myObject = myConstructor.Invoke(null) as IMyClass;

Now... Even using reflection is slow... you could create a dynamic method that invokes the constructor and cache it: 现在...即使使用反射速度也很慢...您可以创建一个动态方法来调用构造函数并将其缓存:

Func<IMyClass> myCreate = Expression.Lambda<Func<IMyClass>>(Expression.New(myConstructor)).Compile();

var myObject = myCreate();

So in the end you could cache only myCreate :-) 所以最后您只能缓存myCreate :-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM