我正在尝试使用MEF创建一个POC,在其中我需要在一个已运行的项目中动态加载dll。为此,我创建了一个控制台应用程序和一个类库项目。
控制台应用程序的代码如下:
namespace MefProjectExtension
{
class Program
{
DirectoryCatalog catalog = new DirectoryCatalog(@"D:\MefDll", "*.dll");
[Import("Method1", AllowDefault = true, AllowRecomposition = true)]
public Func<string> method1;
static void Main(string[] args)
{
AppDomainSetup asp = new AppDomainSetup();
asp.ShadowCopyFiles = "true";
AppDomain sp = AppDomain.CreateDomain("sp",null,asp);
string exeassembly = Assembly.GetEntryAssembly().ToString();
BaseClass p = (BaseClass)sp.CreateInstanceAndUnwrap(exeassembly, "MefProjectExtension.BaseClass");
p.run();
}
}
public class BaseClass : MarshalByRefObject
{
[Import("Method1",AllowDefault=true,AllowRecomposition=true)]
public Func<string> method1;
DirectoryCatalog catalog = new DirectoryCatalog(@"D:\MefDll", "*.dll");
public void run()
{
FileSystemWatcher sw = new FileSystemWatcher(@"D:\MefDll", "*.dll");
sw.NotifyFilter = NotifyFilters.CreationTime | NotifyFilters.Size;
sw.Changed += onchanged;
CompositionContainer container = new CompositionContainer(catalog);
container.ComposeParts(this);
Console.WriteLine(this.method1());
sw.EnableRaisingEvents = true;
Console.Read();
}
void onchanged(object sender, FileSystemEventArgs e)
{
catalog.Refresh();
Console.WriteLine(this.method1());
}
}
}
满足导入外观的库项目如下所示 -
namespace MefLibrary
{
public interface IMethods
{
string Method1();
}
public class CallMethods : IMethods
{
[Export("Method1")]
public string Method1()
{
return "Third6Hello";
}
}
}
一旦我编译了库项目(MefLibrary)并将dll放置在D:\ MefDll位置,并首次运行控制台应用程序,我将看到输出如下: 屏幕上显示Third6hello 但是现在,如果我更改method1的实现并使其返回“third7hello”,则构建MEF Library项目并在我的控制台应用程序正在运行时替换为D:\ MefDll,即使在调用catalog refresh后,onchanged处理程序仍然会打印 屏幕上显示Third6hello 而不是屏幕上显示third7hello 是否有人知道原因? 如果是,请提供帮助。