Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# can't find assembly which is already loaded

Tags:

c#

.net

I am writing an application which uses plugins. Plugins are class libraries which lie in Plug-ins directory. My app loads these libraries via LoadFrom. Some of them have dependencies in the form of libraries which lie in the same Plug-ins directory. When I try to create instance of class from one of plugins via Activator.CreateInstance i recieve an exception 'Unable to find assembly' (this is dependency assembly of plugin), but this assembly is already loaded (!) along with plugins and It is visible in ProcessExplorer. I can't uderstand in what my trouble is.

like image 789
Vasya Avatar asked Nov 22 '11 07:11

Vasya


2 Answers

Your problem might be, that de loaded assembly isn't the same version as the request one. .Net Runtime maps the Assembly after their name and after their Version if the name equals and the Version differes you get an exception if the other one is loaded, which says "Assembly cann't be found" or something like that. The Problem is, that the assembly could not be matched properly. But there is a solution:
Take a look at the MSDN for further information about that Problem.

Solution for that problem:

  1. If you have to load 2 Versions of that assembly try helping the runtime by implementing the AssemblyResolve Event Samples are also here.
  2. Try using the AssemblyBindLogViewer to determine the dependencies of your plugins and to crosscheck your problem.

I recommend implementing the event anyways if you deal with plugins, so you can log all assembly requests of that AppDomain.

You will find furhter information about runtime behavior and assembly loading here

Hope i could help, please give us feedback about your solution!

Configuring the Plugin Folder

  1. Load the Plugins into a seperat AppDomain which has the pluginfolder as ApplicationBase
    To configure AppDomains see. This is the recomendet solution to load Plugins, becaus you can define the security level of the AppDomain (Sandboxing)
  2. Extend your current AppDomains PrivatePath, so it also searches the Assemblies in this Path. This method is Obsolete!(but does it's job)
like image 93
oberfreak Avatar answered Sep 28 '22 03:09

oberfreak


You should provide Full Path of assembly files.

class Program
{
    static void Main(string[] args)
    {
        var asmFileName = "test.dll"; // Your plug-in file name
        var asmPath = AppDomain.CurrentDomain.BaseDirectory; // Your assemblies's root folder
        var asmFullPath = System.IO.Path.Combine(asmPath, asmFileName);
        var asm = System.Reflection.Assembly.LoadFrom(asmFullPath);
    }
}
like image 38
Peter PAD Avatar answered Sep 28 '22 04:09

Peter PAD