C#: Custom assembly directory

前端 未结 4 902
再見小時候
再見小時候 2020-11-27 17:33

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

相关标签:
4条回答
  • 2020-11-27 17:39

    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 set Build 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.

    0 讨论(0)
  • 2020-11-27 17:42

    You can add additional search paths to your app.config that it looks in to load assemblies. For example

    <runtime>
      <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
        <probing privatePath="lib;thirdParty" />
      </assemblyBinding>
    </runtime>
    

    You can see more details here.

    0 讨论(0)
  • 2020-11-27 17:48

    If you want to manually manage where to get assembles from, you have two possibilities:

    1. Handle the AppDomain.AssemblyResolve event (as it is described by SLaks). Here is the code snippet:

      static void Main(string[] args)
      {
         ...
         AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
         ...
      }
      
      static System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
      {
         string assembliesDir = "your_directory";
         Assembly asm = Assembly.LoadFrom(Path.Combine(assembliesDir, args.Name + ".dll"));
         return asm;
      }
      
    2. 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.

    0 讨论(0)
  • 2020-11-27 17:56

    In your comment you mention adding paths and locations at runtime. Yes you can, but you have to use Assembly.Load(), and possibly reflection.

    0 讨论(0)
提交回复
热议问题