我正在为.net核心MVC应用程序实现一个插件架构。我的每个插件的要求是从集中式核心库实现一个接口,然后主mvc应用程序将在每个插件模块中调用已实现的接口方法。
现在我得到我的程序集列表,并从我的.NET Core Startup文件中调用LoadModuleAssemblies方法:
public static void LoadModuleAssemblies(IServiceCollection services, FileInfo[] assemblyList)
{
foreach (var dir in assemblyList)
{
if (dir.Name != CoreLibFile)
{
var asl = new AssemblyLoader(dir.DirectoryName);
var assembly = asl.LoadFromAssemblyPath(dir.FullName);
var implementedList = assembly.GetTypes()
.Where(x => x.GetTypeInfo().ImplementedInterfaces.Contains(typeof(IModule))).ToList();
if (implementedList.Any())
{
services.AddMvc()
.AddApplicationPart(assembly)
.AddControllersAsServices();
//Unsure how to load IModule implemented interface and call GetProperties method in the interface.
}
}
}
}
我的界面看起来像这样:
public interface IModule
{
ModuleProperties GetProperties();
List<string> GetViews();
}
我希望能够为每个插件调用实现的IModule中的GetProperties方法。
我怎样才能做到这一点?
你需要使用Reflection
来创建插件的实例,然后调用它的GetProperties
方法
if (implementedList.Any())
{
services.AddMvc()
.AddApplicationPart(assembly)
.AddControllersAsServices();
foreach(var type in implementedList)
{
var module = Activator.CreateInstance(type) as IModule;
var properties = module.GetProperties();
var views = module. GetViews();
//make use of the properties and views...
}
}