[英]How to extend a C# ASP.NET class if DLL may or may not be available?
Ok, think along the lines of a plugin. 好的,按照插件的思路考虑。
I have my own dll and it has it's own functionality. 我有自己的dll,它具有自己的功能。 If a third-party dll is present, I'm extending a class inside from that dll. 如果存在第三方dll,则表示正在从该dll扩展一个类。
Everything works great except if the third party DLL is missing. 一切都很好,除非缺少第三方DLL。 This is the crux of the problem. 这是问题的症结所在。
I get this exception when the dll is not present: dll不存在时出现此异常:
"Could not load file or assembly 'SOME_THIRD_PARTY_ASSEMBLY, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified." “无法加载文件或程序集'SOME_THIRD_PARTY_ASSEMBLY,版本= 1.0.0.0,区域性=中性,PublicKeyToken =空”或其依赖项之一。系统找不到指定的文件。”
The idea is to allow additional functionality if the third party dll is present, don't allow the functionality if not present. 这个想法是如果存在第三方dll,则允许其他功能,如果不存在,则不允许该功能。
I know I can use Reflection to test whether a type exists, but in order to get to that part of the code, I have to make it past the above exception. 我知道我可以使用Reflection来测试类型是否存在,但是为了到达代码的那一部分,我必须克服上面的异常。
It's not that I JUST need to know if a class is available, I am also extending the class. 并不是我只需要知道一个类是否可用,我也在扩展该类。
So in order for MY dll to compile, I need to add a reference to the third party dll in Visual Studio. 因此,为了编译我的dll,我需要在Visual Studio中添加对第三方dll的引用。
Can I catch this exception somewhere? 我可以在某处捕获此异常吗? Should I go about this differently? 我应该以其他方式去做吗?
You could separate the code that was extending the third party DLL into another DLL. 您可以将将第三方DLL扩展为另一个DLL的代码分开。 Then, in your "extension manager" dll, use a config file to match your extending assemblies with the 3rd party ones. 然后,在您的“扩展管理器” dll中,使用配置文件将扩展程序集与第三方的程序集匹配。
So, the config file could have an item with two entries like "someClass;inSome3rdPartDll" and then "yourClass;inYourDll". 因此,配置文件中的项目可能具有两个条目,例如“ someClass; inSome3rdPartDll”,然后是“ yourClass; inYourDll”。
Go through the config file to see if the listed 3rd party assemblies are present and, if they are, then load you associated assemblies in the app domain. 浏览配置文件以查看是否存在列出的第三方程序集,如果存在,则将您关联的程序集加载到应用程序域中。
Now, if you want to extend future 3rd party assemblies, you need only add your dll and add a line to the config file. 现在,如果要扩展将来的第三方程序集,只需添加dll并在配置文件中添加一行即可。
Here's a link for help loading assemblies into app domains. 这是帮助将程序集加载到应用程序域中的链接 。
You could also look into MEF and leverage composition to accomplish this. 您也可以研究MEF并利用组合来完成此任务。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.