简体   繁体   中英

Load all provider classes from a solution folder

Given a .net application that supports different logic providers, how to instantiate one instance of each class in a solution folder? What is the way to iterate through all of the classes in the folder?

For example I have a folder in my solution called MailClientProviders It contains Outlook and The Bat! provider classes that implement a IMailProvider interface.

In my App.xaml I call a Ninject container to initialize all the dependencies. Then I need to write a method that I would call, and would get an instance of each class returned.

heartbeatService.Providers = CreateOneInstanceOfAllClassesInProvidresDir(MailClientProviders);

What would be in the CreateOneInstanceOfAllClassesInProvidresDir method?

Directory.GetFiles("MailClientProviders", "*.dll")来获取文件夹内的所有DLL,然后Assembly.LoadFrom每个返回的结果和每个装配Assembly.GetTypes让所有的公共类型和每种类型是否实现检查必需的接口,以及是否使用Activator.CreateInstance实例化它。

I used these functions to retrieve all classes in a folder implementing my custom interface:

public static List<T> GetFilePlugins<T>(string filename)
{
    List<T> ret = new List<T>();
    if (File.Exists(filename))
    {
        Type typeT = typeof(T);
        Assembly ass = Assembly.LoadFrom(filename);
        foreach (Type type in ass.GetTypes())
        {
            if (!type.IsClass || type.IsNotPublic) continue;
            if (typeT.IsAssignableFrom(type))
            {
                T plugin = (T)Activator.CreateInstance(type);
                ret.Add(plugin);
            }
        }
    }
    return ret;
}
public static List<T> GetDirectoryPlugins<T>(string dirname)
{
    List<T> ret = new List<T>();
    string[] dlls = Directory.GetFiles(dirname, "*.dll");
    foreach (string dll in dlls)
    {
        List<T> dll_plugins = GetFilePlugins<T>(Path.GetFullPath(dll));
        ret.AddRange(dll_plugins);
    }
    return ret;
}

So you can run GetDirectoryPlugins<IMailProvider> and use Activator.CreateInstance with every class found...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM