我有一个情况,我需要知道如何以最好的方式处理它.
我有一个应用程序(MVC3),我有几个集成.我有一个接口"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);
}
}
Run Code Online (Sandbox Code Playgroud)
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
}
Run Code Online (Sandbox Code Playgroud)