S
S
Sergey K2018-03-29 15:30:16
C++ / C#
Sergey K, 2018-03-29 15:30:16

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

1 answer(s)
A
Alexander Yudakov, 2018-03-29
@AceLightning

var assembly = Assembly.LoadFrom("c:\plugins\table.dll");
var type = assembly.GetType("MyNamespace.Table");
var instance = (ITable) Activator.CreateInstance(type);

PS An example of a complete working solution:
Common.dll/IPlugin.cs
namespace Common
{
    public interface IPlugin
    {
        string GetName();
    }
}
Plugin.dll / Plugin.cs
using Common;

namespace Plugin
{
    public sealed class Plugin : IPlugin
    {
        public string GetName()
        {
            return "Cool Plugin!";
        }
    }
}
PluginsTest.exe / Program.cs
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);
        }
    }
}

Dependencies:
Plugin.dll → Common.dll
PluginsTest.exe → Common.dll

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question