Ajit Hegde Ajit Hegde - 1 month ago 6
C# Question

could not load assemly error when try to load plugins in c#

I want to create a Plugin architecture so I created the following interface

public interface IPlug
{
string Id { get; }

string Name { get; }

byte IsOn { get; }

bool Execute();
}


Now I reference the above interface to another class library project.

namespace PlugANameSpace
{
public class PlugA : IPlug
{
private byte _isOn;

public string Id
{
get {return "6666"; }
}

public byte IsOn
{
get { return _isOn; }
}

public string Name
{
get { return "PlugA"; }
}

public PlugA()
{

LoadFromRegistry();
}

public bool Execute()
{
// do some thing that returns true for success or false for error
}

private void LoadFromRegistry()
{
//register in registry
}
}
}


The above class library is copied into the main assembly file and stored in a folder "Plugins". Then I tried to load the plugin with the following code.

IPlug plug= Activator.CreateInstanceFrom(file, typeof(IPlug).FullName) as IPlug;


file is dll file got from
Directory.GetFiles
method.
When I tried to create instance, it throws error " Could not load type 'IPlug ' from assembly 'PlugA, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. "

what I am doing wrong.?

Answer

You need to specify the name of the type in the PlugA assembly.

IPlug plug = Activator.CreateInstanceFrom(file, "PlugANameSpace.PlugA") as IPlug;

Edit: If you want to load a plugin without knowing the name of the type:

var assembly = Assembly.Load(file);
var pluginType = assembly.GetTypes().FirstOrDefault(t => typeof(IPlug).IsAssignableFrom(t));
IPlug plug = Activator.CreateInstance(pluginType) as IPlug;
Comments