2

How to reference a dll outside the application's folder and utilize its methods and interfaces with loading it dynamically? is there a way to do that?

Note: the reference must be made from that path even after the application gets deployed.

2 Answers2

1

I would try using Assembly.LoadFrom(string). This overload takes the path to the assembly and allows you to utilize it via reflection.

You can get the assembly like this:

var sampleAssembly = Assembly.LoadFrom("c:\\Sample.Assembly.dll");
var method = sampleAssembly.GetTypes()[0].GetMethod("Method1");

Then invoke that method using MethodInfo.Invoke()

Nate
  • 30,286
  • 23
  • 113
  • 184
1

There are many ways to do that. Detailed explanation of how runtime locates assemblies can be found at How runtime locates assemblies.

You can specify exact location via codeBase element in app.config:

<configuration>  
   <runtime>  
      <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">  
         <dependentAssembly>  
            <assemblyIdentity name="myAssembly"  
                              publicKeyToken="32ab4ba45e0a69a1"  
                              culture="neutral" />  
            <codeBase version="2.0.0.0"  
                      href="http://www.litwareinc.com/myAssembly.dll"/>  
         </dependentAssembly>  
      </assemblyBinding>  
   </runtime>  
</configuration> 

If your assembly is in subfolder of application then you can use probing element:

<configuration>  
   <runtime>  
      <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">  
         <probing privatePath="bin;bin2\subbin;bin3"/>  
      </assemblyBinding>  
   </runtime>  
</configuration>

If all that fails, you can always write event handler and attach it to AppDomain.AssemblyResolve to explicitly load assemblies. There is even example on SO.

nejcs
  • 1,212
  • 10
  • 14
  • What If it is in a different folder other than the application itself and that dll's version changes very often ? – user7380740 Aug 10 '17 at 19:21
  • Then you will have to go with `AppDomain.AssemblyResolve` route. Somewhere at the entry point of application, register handler which will be called when loader could not load assembly by regular mechanism. Inside handler you will find assembly yourself, load it with `Assembly.LoadFrom` and return it. Look at the example from similar SO question that I linked to. – nejcs Aug 10 '17 at 19:32
  • My issue is the root dll must be in the application path(C:\Program Files\RING) and others must be in a different location (C:\Program Files\ThirdParty). can this be achieved without dynamic loading and the reference must be made to the thirdparty folder even after deploying? – user7380740 Aug 10 '17 at 23:44