我正在尝试使用 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 库项目并在 D:\MefDll 替换,而我的控制台应用程序正在运行 onchanged 处理程序,即使在调用目录刷新后 也会在屏幕上打印 Third6hello 而不是third7hello
是否有人知道这是什么原因,如果是,请帮忙。