I have faced a strange situation recently which I do not understand and ask someone of you to describe me what I did wrong or what I am missing here.
The solution is build from 3 projects (some of code parts has been cut out to make it more readable):
namespace TestRun
{
class Program
{
static void Main(string[] args)
{
Assembly assembly = Assembly.LoadFrom(PluginPath);
foreach (Type type in assembly.GetTypes())
{
if (type.IsSubclassOf(Plugins.Plugin) &&
type.IsAbstract == false)
{
if(Parameters != null && Parameters.Length > 0)
Result = (T) Activator.CreateInstance(type, Parameters);
else
Result = (T) Activator.CreateInstance(type);
}
}
}
}
}
This one is responsible for loading all files with dll extension from a given folder (plugins).
Next I have a main plugin class:
namespace Plugins
{
public interface IPlugin
{
void func();
}
public abstract class Plugin : IPlugin
{
//Basic implementation
}
}
And a plugin assemblies:
namespace DevicePlugins
{
public class DevicePlugin : Plugins.Plugin
{
{...}
}
}
The problem is that if Project 1 has the reference to the plugin assembly (i.E. DevicePlugins) it cannot create an instance of an object from this assembly (DevicePlugin). I do not get any error or exception - only information about "Result" from Project 1 - "Value cannot be evaluated". If I remove the reference to the plugin's assembly from Project 1 (I mean that in the Project 1 I have not the reference to DevicePlugins assembly) everything is working like a charm (I can create an object of DevicePlugin from DevicePlugins assembly). Moreover, when I have the reference I can initiate an object in the normal way
DevicePlugins.DevicePlugin plug = new DevicePlugins.DevicePlugin();
Can someone tell me what am I missing or do not understand?? Why it working in that way?
When you add an assembly reference to a project, it builds a dependency on the assembly into the executable and this causes the assembly to be loaded at runtime into the execution context.
As you are actually loading the same assembly twice into the execution context (once manually using LoadFrom
, once by assembly reference), you should check the behaviour of LoadFrom
for your specific case. If you are doing what I think you are, which is loading the assembly from a "plugins" folder, then LoadFrom
will start behaving incorrectly with regards to what you want to achieve, I believe.
Read up on MSDN for the specifics: http://msdn.microsoft.com/en-us/library/1009fa28(v=vs.110).aspx