Finding objects that implement interface from loaded assembly -how to compare types?

后端 未结 1 1495
难免孤独
难免孤独 2021-01-03 06:37

I have class that will load all assemblies in a directory and then get all the types an see if they implement an interface. I cannot get the type comparison to work. In the

1条回答
  •  伪装坚强ぢ
    2021-01-03 07:00

    OK - this gave me the answer: invalidcastexception-when-using-assembly-loadfile

    Here is the updated class:

    public class PluginLoader
    {
        public static T[] GetInterfaceImplementor(string directory)
        {
            if (String.IsNullOrEmpty(directory)) { return null; } //sanity check
    
            DirectoryInfo info = new DirectoryInfo(directory);
            if (!info.Exists) { return null; } //make sure directory exists
    
            var implementors = new List();
    
            foreach (FileInfo file in info.GetFiles("*.dll")) //loop through all dll files in directory
            {
                Assembly currentAssembly = null;
                try
                {
                    var name = AssemblyName.GetAssemblyName(file.FullName);
                    currentAssembly = Assembly.Load(name);
                }
                catch (Exception ex)
                {
                    continue;
                }
    
                currentAssembly.GetTypes()
                    .Where(t => t != typeof(T) && typeof(T).IsAssignableFrom(t))
                    .ToList()
                    .ForEach(x => implementors.Add((T)Activator.CreateInstance(x)));
            }
            return implementors.ToArray();
        }
    }
    

    0 讨论(0)
提交回复
热议问题