C# 获取DLL中需要的接口类

[ 需求 ]

使用反射,循环本地DLL文件,获取实现了所需接口的类,并实例化。

Loop local dll files by reflection library and assembly library to find all the classes that implement certain interface and create instances for them.

二话不说,先上代码。

Talk is cheap. Show me the code.

 1 using System;
 2 using System.Collections.Generic;
 3 using System.IO;
 4 using System.Linq;
 5 using System.Reflection;
 6 
 7 namespace InterfaceClassLoader
 8 {
 9     public class Loader
10     {
11 
12         private List<IMyInterface> myInstanceList;
13         private void Initialize()
14         {
15 
16             try
17             {
18                 var type= typeof(IMyInterface);
19                 myInstanceList= GetAllAssemblies().
20                     SelectMany(a => a.GetTypes()).
21                     Where(t => !t.IsInterface && type.IsAssignableFrom(t)).
22                     Select(t => (IMyInterface)Activator.CreateInstance(t)).ToList();
23             }
24             catch (Exception ex)
25             {}
26         }
27 
28 
29         private List<Assembly> GetAllAssemblies()
30         {
31             var folderPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
32             var allAssemblies = new List<Assembly>();
33             Directory.GetFiles(folderPath,"*.dll").ToList().ForEach(f => 
34             {
35                 allAssemblies.Add(Assembly.LoadFile(f));
36             });
37 
38 
39             var filteredAssembly = allAssemblies.FindAll(a => a.FullName.Contains("MyMark"));
40             return filteredAssembly;
41         }
42 
43     }      
44 
45 }

 

posted @ 2019-06-18 13:30  No5Meters  阅读(1311)  评论(0编辑  收藏  举报