在多个模块化插件中的实现接口内执行方法

问题描述 投票:0回答:1

我正在为.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方法。

我怎样才能做到这一点?

c# asp.net-mvc plugins asp.net-core
1个回答
1
投票

你需要使用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...
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.