How To Create Plugins That Can Be Loaded Unloaded

How to create plugins that can be loaded/unloaded

Hello everybody,

today I want to show sample of code that you can use for your plugins.

Sometime it can happen that you have some application with it's dlls and you can decide to make ad hoc dlls.

In order to demonstrate how to do it I prepared following code:

Create first class library as BaseLib:

using System;
 
namespace BaseClass
{
    public class BaseClass : MarshalByRefObject
    {
        public virtual bool IsProcessable(string message)
        {
            return true;
        }
 
        public virtual void Process(string message)
        {
            
        }
    }
}

Then create following implementation:

using System;
namespace Ext1
{
    public class Extension1 : BaseClass.BaseClass
    {
        public override bool IsProcessable(string message)
        {
            return true;
        }
 
        public override void Process(string message)
        {
            message = message + " 1 " + message;
            Console.WriteLine(message);
        }
    }
}

And then code like this will give you possibility to load/unload dlls:

using System;
using System.IO;
using System.Reflection;
 
namespace MarshalByRef
{
    class Program
    {
        static void Main(string[] args)
        {
            AppDomain ad = AppDomain.CreateDomain("extensions");
            string testDlls = @"d:\sources\MarshalByRef\MarshalByRef\destDlls\";
            string dest = @"d:\sources\MarshalByRef\MarshalByRef\MarshalByRef\bin\Debug\" + "Ext1.dll";
            File.Copy(testDlls + "Ext1.dll", dest, true);
 
            Loader loader = (Loader)ad.CreateInstanceAndUnwrap(typeof(Loader).Assembly.FullName, typeof(Loader).FullName);
            loader.LoadAssembly(dest);
            loader.Execute();
            //if you try to delete Ext1.dll you'll got an error
            AppDomain.Unload(ad);
            //if you try to delete Ext1.dll now, you'll be successfull
            Console.ReadKey();
        }
    }
 
    class Loader : MarshalByRefObject
    {
        private Assembly _assembly;
 
        public void LoadAssembly(string path)
        {
            _assembly = Assembly.Load(AssemblyName.GetAssemblyName(path));
        }
 
        public void Execute()
        {
            var instance = _assembly.CreateInstance("Ext1.Extension1"as BaseClass.BaseClass;
            instance.Process("test");
        }
    }
}

No Comments

Add a Comment
Comments are closed