我遇到了一种情况,我需要知道如何以最好的方式处理它。
我有一个应用程序 (MVC3),并且我有几个集成。我有一个接口(interface)“IntegrationInterface”,每个集成都实现它。 我想加载集成的 dll,创建它们的列表,然后运行一个循环,为列表中的每个集成运行一个方法。
例如 - 假设我集成了 facebook、myspace 和 twitter(对于我的应用程序),每次用户在我的应用程序中发布消息时,我想在他/她的 facebook、myspace 和 twitter 上发布消息。
我不希望代码知道我有哪些集成,所以如果明天我要为 google+ 创建一个新的集成,我只需要添加一个新的 DLL,而无需更改我的应用程序的代码。
我怎样才能做到这一点?
最佳答案
首先,您必须找到所有相关的 dll 和类:
loadedIntegrations.Clear();
if (!Directory.Exists(path))
return;
DirectoryInfo di = new DirectoryInfo(path);
FileInfo[] files = di.GetFiles("*.dll");
foreach (var file in files)
{
Assembly newAssembly = Assembly.LoadFile(file.FullName);
Type[] types = newAssembly.GetExportedTypes();
foreach (var type in types)
{
//If Type is a class and implements the IntegrationInterface interface
if (type.IsClass && (type.GetInterface(typeof(IntegrationInterface).FullName) != null))
loadedIntegrations.Add(type);
}
}
loadedIntegrations
类型为List<Type>
。然后您可以实例化每个集成并调用其方法:
foreach(var integrationType in loadedIntegrations)
{
var ctor = integrationType.GetConstructor(new Type[] { });
var integration = ctor.Invoke(new object[] { }) as IntegrationInterface;
//call methods on integration
}
关于C# - 加载 dll 并创建实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11491431/