- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
目前,我配置了一个模块文件夹,我所有的模块程序集及其依赖项都放在那里。我担心六个月后,有人构建了一个新模块,它的依赖项会覆盖旧版本的依赖项。
我是否应该开发某种模块注册表,开发人员可以在其中注册一个新模块,并在模块文件夹中为其分配一个子文件夹名称?但是,如果我必须告诉主机有关模块的信息,这种情况会降低使用 DirectoryCatalog
的便利性。
最佳答案
我以前遇到过类似的问题。下面我介绍我的解决方案,我认为这与您要实现的目标相似。
像这样使用 MEF 真的很有趣,但这里是我的警告:
MarshalByRefObject
和不使用解决方案构建的插件好吧,免责声明……
.NET 允许您将同一程序集的多个版本加载到内存中,但不能卸载它们。这就是为什么我的方法需要 AppDomain 以允许您在新版本可用时卸载模块。
下面的解决方案允许您在运行时将插件 dll 复制到 bin 目录中的“plugins”文件夹中。随着新插件的添加和旧插件的覆盖,旧插件将被卸载,新插件将被加载,而无需重新启动您的应用程序。如果您的目录中同时有多个不同版本的 dll,您可能需要修改 PluginHost
以通过文件的属性读取程序集版本并相应地执行操作。
一共有三个项目:
ConsoleApplication.dll
class Program
{
static void Main(string[] args)
{
var pluginHost = new PluginHost();
//Console.WriteLine("\r\nProgram:\r\n" + string.Join("\r\n", AppDomain.CurrentDomain.GetAssemblies().Select(a => a.GetName().Name)));
pluginHost.CallEach<ITestPlugin>(testPlugin => testPlugin.DoSomething());
//Console.ReadLine();
}
}
集成.dll
PluginHost 允许您与插件通信。应该只有一个 PluginHost 实例。这也充当轮询 DirectoryCatalog
。
public class PluginHost
{
public const string PluginRelativePath = @"plugins";
private static readonly object SyncRoot = new object();
private readonly string _pluginDirectory;
private const string PluginDomainName = "Plugins";
private readonly Dictionary<string, DateTime> _pluginModifiedDateDictionary = new Dictionary<string, DateTime>();
private PluginDomain _domain;
public PluginHost()
{
_pluginDirectory = AppDomain.CurrentDomain.BaseDirectory + PluginRelativePath;
CreatePluginDomain(PluginDomainName, _pluginDirectory);
Task.Factory.StartNew(() => CheckForPluginUpdatesForever(PluginDomainName, _pluginDirectory));
}
private void CreatePluginDomain(string pluginDomainName, string pluginDirectory)
{
_domain = new PluginDomain(pluginDomainName, pluginDirectory);
var files = GetPluginFiles(pluginDirectory);
_pluginModifiedDateDictionary.Clear();
foreach (var file in files)
{
_pluginModifiedDateDictionary[file] = File.GetLastWriteTime(file);
}
}
public void CallEach<T>(Action<T> call) where T : IPlugin
{
lock (SyncRoot)
{
var plugins = _domain.Resolve<IEnumerable<T>>();
if (plugins == null)
return;
foreach (var plugin in plugins)
{
call(plugin);
}
}
}
private void CheckForPluginUpdatesForever(string pluginDomainName, string pluginDirectory)
{
TryCheckForPluginUpdates(pluginDomainName, pluginDirectory);
Task.Delay(5000).ContinueWith(task => CheckForPluginUpdatesForever(pluginDomainName, pluginDirectory));
}
private void TryCheckForPluginUpdates(string pluginDomainName, string pluginDirectory)
{
try
{
CheckForPluginUpdates(pluginDomainName, pluginDirectory);
}
catch (Exception ex)
{
throw new Exception("Failed to check for plugin updates.", ex);
}
}
private void CheckForPluginUpdates(string pluginDomainName, string pluginDirectory)
{
var arePluginsUpdated = ArePluginsUpdated(pluginDirectory);
if (arePluginsUpdated)
RecreatePluginDomain(pluginDomainName, pluginDirectory);
}
private bool ArePluginsUpdated(string pluginDirectory)
{
var files = GetPluginFiles(pluginDirectory);
if (IsFileCountChanged(files))
return true;
return AreModifiedDatesChanged(files);
}
private static List<string> GetPluginFiles(string pluginDirectory)
{
if (!Directory.Exists(pluginDirectory))
return new List<string>();
return Directory.GetFiles(pluginDirectory, "*.dll").ToList();
}
private bool IsFileCountChanged(List<string> files)
{
return files.Count > _pluginModifiedDateDictionary.Count || files.Count < _pluginModifiedDateDictionary.Count;
}
private bool AreModifiedDatesChanged(List<string> files)
{
return files.Any(IsModifiedDateChanged);
}
private bool IsModifiedDateChanged(string file)
{
DateTime oldModifiedDate;
if (!_pluginModifiedDateDictionary.TryGetValue(file, out oldModifiedDate))
return true;
var newModifiedDate = File.GetLastWriteTime(file);
return oldModifiedDate != newModifiedDate;
}
private void RecreatePluginDomain(string pluginDomainName, string pluginDirectory)
{
lock (SyncRoot)
{
DestroyPluginDomain();
CreatePluginDomain(pluginDomainName, pluginDirectory);
}
}
private void DestroyPluginDomain()
{
if (_domain != null)
_domain.Dispose();
}
}
Autofac 是此代码的必需依赖项。 PluginDomainDependencyResolver 在插件 AppDomain 中实例化。
[Serializable]
internal class PluginDomainDependencyResolver : MarshalByRefObject
{
private readonly IContainer _container;
private readonly List<string> _typesThatFailedToResolve = new List<string>();
public PluginDomainDependencyResolver()
{
_container = BuildContainer();
}
public T Resolve<T>() where T : class
{
var typeName = typeof(T).FullName;
var resolveWillFail = _typesThatFailedToResolve.Contains(typeName);
if (resolveWillFail)
return null;
var instance = ResolveIfExists<T>();
if (instance != null)
return instance;
_typesThatFailedToResolve.Add(typeName);
return null;
}
private T ResolveIfExists<T>() where T : class
{
T instance;
_container.TryResolve(out instance);
return instance;
}
private static IContainer BuildContainer()
{
var builder = new ContainerBuilder();
var assemblies = LoadAssemblies();
builder.RegisterAssemblyModules(assemblies); // Should we allow plugins to load dependencies in the Autofac container?
builder.RegisterAssemblyTypes(assemblies)
.Where(t => typeof(ITestPlugin).IsAssignableFrom(t))
.As<ITestPlugin>()
.SingleInstance();
return builder.Build();
}
private static Assembly[] LoadAssemblies()
{
var path = AppDomain.CurrentDomain.BaseDirectory + PluginHost.PluginRelativePath;
if (!Directory.Exists(path))
return new Assembly[]{};
var dlls = Directory.GetFiles(path, "*.dll").ToList();
dlls = GetAllDllsThatAreNotAlreadyLoaded(dlls);
var assemblies = dlls.Select(LoadAssembly).ToArray();
return assemblies;
}
private static List<string> GetAllDllsThatAreNotAlreadyLoaded(List<string> dlls)
{
var alreadyLoadedDllNames = GetAppDomainLoadedAssemblyNames();
return dlls.Where(dll => !IsAlreadyLoaded(alreadyLoadedDllNames, dll)).ToList();
}
private static List<string> GetAppDomainLoadedAssemblyNames()
{
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
return assemblies.Select(a => a.GetName().Name).ToList();
}
private static bool IsAlreadyLoaded(List<string> alreadyLoadedDllNames, string file)
{
var fileInfo = new FileInfo(file);
var name = fileInfo.Name.Replace(fileInfo.Extension, string.Empty);
return alreadyLoadedDllNames.Any(dll => dll == name);
}
private static Assembly LoadAssembly(string path)
{
return Assembly.Load(File.ReadAllBytes(path));
}
}
此类代表实际的插件 AppDomain。解析到该域中的程序集应该首先从 bin/plugins 文件夹加载它们需要的任何依赖项,然后是 bin 文件夹,因为它是父 AppDomain 的一部分。
internal class PluginDomain : IDisposable
{
private readonly string _name;
private readonly string _pluginDllPath;
private readonly AppDomain _domain;
private readonly PluginDomainDependencyResolver _container;
public PluginDomain(string name, string pluginDllPath)
{
_name = name;
_pluginDllPath = pluginDllPath;
_domain = CreateAppDomain();
_container = CreateInstance<PluginDomainDependencyResolver>();
}
public AppDomain CreateAppDomain()
{
var domaininfo = new AppDomainSetup
{
PrivateBinPath = _pluginDllPath
};
var evidence = AppDomain.CurrentDomain.Evidence;
return AppDomain.CreateDomain(_name, evidence, domaininfo);
}
private T CreateInstance<T>()
{
var assemblyName = typeof(T).Assembly.GetName().Name + ".dll";
var typeName = typeof(T).FullName;
if (typeName == null)
throw new Exception(string.Format("Type {0} had a null name.", typeof(T).FullName));
return (T)_domain.CreateInstanceFromAndUnwrap(assemblyName, typeName);
}
public T Resolve<T>() where T : class
{
return _container.Resolve<T>();
}
public void Dispose()
{
DestroyAppDomain();
}
private void DestroyAppDomain()
{
AppDomain.Unload(_domain);
}
}
最后是您的插件接口(interface)。
public interface IPlugin
{
// Marker Interface
}
主应用程序需要了解每个插件,因此需要一个接口(interface)。它们必须继承IPlugin
并注册到PluginHost
BuildContainer
方法
public interface ITestPlugin : IPlugin
{
void DoSomething();
}
测试插件.dll
[Serializable]
public class TestPlugin : MarshalByRefObject, ITestPlugin
{
public void DoSomething()
{
//Console.WriteLine("\r\nTestPlugin:\r\n" + string.Join("\r\n", AppDomain.CurrentDomain.GetAssemblies().Select(a => a.GetName().Name)));
}
}
最后的想法...
此解决方案对我有用的一个原因是我的 AppDomain 插件实例的生命周期非常短。但是,我相信可以进行修改以支持具有更长生命周期的插件对象。这可能需要一些妥协,例如更高级的插件包装器,它可能会在重新加载 AppDomain 时重新创建对象(请参阅 CallEach
)。
关于c# - 我如何处理 MEF 中具有相同依赖项的不同版本的模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21399196/
是 if(a == 0 && b == 0 && c == 0) { return; } 一样 if(a == 0) { return; } if(b == 0) { return; } if(c =
我想做这样的事情: Class A Class B extends A Class C extends A B b = new B(); C c = new C(); b->setField("foo
我对 Mysql 世界很天真......:)我试图使用连接从表中查询, 我遇到结果集问题...表结构如下 下面... VIDEO_XXXXX | Field | Type
我最近问过关于从另一个类获取类的唯一实例的问题。 ( How to get specific instance of class from another class in Java? ) 所以,我正
假设我们有两种类型 using t1 = int*; using t2 = int*; 我知道 std::is_same::value会给我们true .什么是,或者是否有模板工具可以实现以下目标?
对于我的一个应用程序,我假设比较 2 个字符串的第一个字符比比较整个字符串是否相等要快。例如,如果我知道只有 2 个可能的字符串(在一组 n 字符串中)可以以相同的字母开头(比如说 'q'),如果是这
我想在我的NXP LPC11U37H主板(ARM Cortex-M0)上分析一些算法,因为我想知道执行特定算法需要多少个时钟周期。 我编写了这些简单的宏来进行一些分析: #define START_C
我在 Excel 中创建了一个宏,它将在 Excel 中复制一个表格,并将行除以我确定的特定数字(默认 = 500 行),并为宏创建的每个部门打开不同的工作表。 使用的代码是这样的: Sub Copy
我想根据第一个字典对第二个字典的值求和。如果我有字典 A 和 B。 A = {"Mark": ["a", "b", "c", "d"], "June": ["e", "a"], "John": ["a
当我这样做时 system()在 Perl 中调用,我通常根据 perldocs 检查返回码.嗯,我是这么想的。大部分时间 $rc!=0对我来说已经足够了。最近我在这里帮助了两个遇到问题的人syste
在我的进度条上,我试图让它检测 div 加载速度。 如果 div 加载速度很快,我想要实现的目标将很快达到 100%。但进度条的加载速度应该与 div 的加载速度一样快。 问题:如何让我的进度条加载
当我获得与本地时间相同的时间戳时,firebase 生成的服务器时间戳是否会自动转换为本地时间,或者我错过了什么? _firestore.collection("9213903123").docume
根据the original OWL definition of OWL DL ,我们不能为类和个体赋予相同的名称(这是 OWL DL 和 OWL Full 之间的明显区别)。 "Punning" i
我有两个输入复选框: 尝试使用 jQuery 来允许两个输入的行为相同。如果选中第一个复选框,则选中第二个复选框。如果未检查第 1 个,则不会检查第 2 个。反之亦然。 我有代码: $('inpu
可以从不同系统编译两个相同的java文件,但它们都有相同的内容操作系统(Windows 7),会生成不同的.class文件(大小)? 最佳答案 是的,您可以检查是否有不同版本的JDK(Java Dev
我正在清理另一个人的正则表达式,他们目前所有的都以结尾 .*$ 那么下面的不是完全一样吗? .* 最佳答案 .*将尽可能匹配,但默认情况下为 .不匹配换行符。如果您要匹配的文本有换行符并且您处于 MU
我使用 Pick ,但是如何编写可以选择多个字段的通用PickMulti呢? interface MyInterface { a: number, b: number, c: number
我有一个 SQL 数据库服务器和 2 个具有相同结构和数据的数据库。我在 2 个数据库中运行相同的 sql 查询,其中一个需要更长的时间,而另一个在不到 50% 的时间内完成。他们都有不同的执行计划。
我需要你的帮助,我有一个包含两列的表,一个 id 和 numpos,我希望 id 和 numops 具有相同的结果。 例子: $cnx = mysql_connect( "localhost", "r
如何将相同的列(在本例中按“级别”排序)放在一起?我正在做一个高分,我从我的数据库中按级别列出它们。如果他们处于同一级别,我希望他们具有相同的 ID。 但是我不想在别人身上显示ID。只有第一个。这是一
我是一名优秀的程序员,十分优秀!