Answer the question
In order to leave comments, you need to log in
How to instantiate a class from a dynamically linked DLL?
There is a DLL that has a Table class that implements the ITable interface.
There is a program that needs to create an instance of the Table class that implements the ITable interface from a dynamically linked DLL. The question is how to implement all this?
Answer the question
In order to leave comments, you need to log in
var assembly = Assembly.LoadFrom("c:\plugins\table.dll");
var type = assembly.GetType("MyNamespace.Table");
var instance = (ITable) Activator.CreateInstance(type);
namespace Common
{
public interface IPlugin
{
string GetName();
}
}
using Common;
namespace Plugin
{
public sealed class Plugin : IPlugin
{
public string GetName()
{
return "Cool Plugin!";
}
}
}
using Common;
using System;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
namespace PluginsTest
{
class Program
{
static void Main(string[] args)
{
var plugin = LoadPlugin("..\\..\\..\\Plugin\\bin\\Debug\\Plugin.dll");
var name = plugin.GetName();
Debug.WriteLine("Plugin loaded: " + name);
}
static IPlugin LoadPlugin(string path)
{
var type = Assembly
.LoadFrom(path)
.GetTypes()
.First(typeof(IPlugin).IsAssignableFrom);
return (IPlugin)Activator.CreateInstance(type);
}
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question