假设我们有一个由 1 个可执行文件和 5 个库组成的应用程序。通常,所有这些都将包含在一个目录中,并且将从该目录加载库。
是否可以这样做,例如,我可以将一些库放在一个名为 Lib 的目录中,而将其余库放在一个名为 Lib2 的目录中?这样应用程序目录将只包含可执行文件本身,其他程序集将包含在各种逻辑目录中。
我该怎么做?我想知道如何加载程序集,以及如何使应用程序的构建将程序集放在正确的目录中。
Say we have an application which consists of one executable and 5 libraries. Regularly all of these will be contained in one directory and the libraries will be loaded from there.
Is it possible to do so that I can have for example some of the libraries in one directory called Lib, and the rest in one called Lib2? So that the application directory would only contain the executable itself and the other assemblies would be contained in various logical directories.
How can I do this? And I would like to know how to do the loading of the assemblies, but also how to make the building of the application put the assemblies in the right directory.
发布评论
评论(4)
您可以向 app.config 添加其他搜索路径,以供其查找以加载程序集。例如,
您可以在此处。
You can add additional search paths to your app.config that it looks in to load assemblies. For example
You can see more details here.
如果您想手动管理从何处获取汇编,您有两种可能性:
处理AppDomain.AssemblyResolve 事件(如 SLAks 所描述)。这是代码片段:
使用您自己的设置创建域(通过设置 ApplicationBase 或 PrivateBinPath AppDomainSetup 对象的属性)。
因此,如果您想继续在当前域中工作,则必须使用方法 1。
If you want to manually manage where to get assembles from, you have two possibilities:
Handle the AppDomain.AssemblyResolve event (as it is described by SLaks). Here is the code snippet:
Create a domain with your own settings (by setting ApplicationBase or PrivateBinPath properties of the AppDomainSetup object).
So if you want to continue working in current domain you have to use method 1.
要自动将程序集复制到您希望它们所在的文件夹,您可以将所有引用的“Copy Local”设置为 true,并执行构建后步骤将它们移动到子目录中。
或者,您可以将“Copy Local”设置为 false,并将引用的 DLL 文件添加为项目中相应子目录中的文件,并将“Build Action”设置为“复制到输出目录”(这将保留子目录)
让运行时找到它们的最灵活方法是处理 AppDomain.AssemblyResolve 事件并使用 Assembly.LoadFile。您需要某种方式让您的代码知道哪些程序集位于哪些目录中。
To make automatically copy the assemblies to the folder you want them to be in, you could set
Copy Local
to true for all of the references, and make a post-build step to move them into subdirectories.Alternatively, you could set
Copy Local
to false, and add the referenced DLL files as files in the project in the appropriate subdirectories, and setBuild Action
to Copy to output directory (This will preserve subdirectories)The most flexible way to make the runtime find them is to handle the AppDomain.AssemblyResolve event and manually load the assembly using Assembly.LoadFile. You would need some way for your code to know which assemblies are in which directories.
在您的评论中,您提到在运行时添加路径和位置。是的,您可以,但是您必须使用 Assembly.Load(),并且可能还需要使用反射。
In your comment you mention adding paths and locations at runtime. Yes you can, but you have to use Assembly.Load(), and possibly reflection.