闲言不讲,直接上代码,如下三个文件,分属三个项目。
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Remoting.Lifetime;
using System.Text;
using Contract;
namespace Application
{
class Program
{
/// <summary>
/// 构建一个AppDomainSetup实例
/// 用于启用卷影复制并设置基本路径
/// </summary>
public static AppDomainSetup CreateAppDomainSetup()
{
AppDomainSetup setup = new AppDomainSetup();
setup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory;
setup.ShadowCopyFiles = "true";
return setup;
}
/// <summary>
/// 从当前目录下的指定的程序集文件中加载指定的类型
/// </summary>
public static object CreateAndUnwrap(AppDomain appDomain, string assemblyFile, string typeName)
{
string fullName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, assemblyFile);
return appDomain.CreateInstanceFromAndUnwrap(fullName, typeName);
}
static void Main()
{
Console.WriteLine("Current AppDomain:{0}",
AppDomain.CurrentDomain.FriendlyName);
AppDomainSetup setup = CreateAppDomainSetup();
//建立准备加载插件的AppDomain
AppDomain secAppDomain = AppDomain.CreateDomain("SecAppDomain", null, setup);
//忽略新建立的AppDomain里面的调用租约管理
secAppDomain.DoCallBack(delegate
{
LifetimeServices.LeaseTime = TimeSpan.Zero;
});
IAddin addinOne = (IAddin)CreateAndUnwrap(
secAppDomain, "Implement.dll", "Implement.AddinOne");
Console.WriteLine(addinOne.Run("Test"));
//卸载装入插件的AppDomain
AppDomain.Unload(secAppDomain);
//由于插件所在的AppDmain已被卸载,所以以下的执行会出现异常
try
{
Console.WriteLine(addinOne.Run("Test"));
}
catch (Exception ex)
{
Console.WriteLine("发生调用异常:" + ex.Message);
}
Console.ReadLine();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Contract
{
public interface IAddin
{
string Run(string paramString);
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Contract;
namespace Implement
{
public class AddinOne:MarshalByRefObject,IAddin
{
public string Run(string paramString)
{
const string resultString =
"Current AppDomain:{0},Param String:{1}!";
return string.Format(
resultString,
AppDomain.CurrentDomain.FriendlyName,
paramString);
}
}
}