如何在不知道c#.net中的名称的情况下从文件夹加载所有dll?

时间:2016-01-18 16:24:59

标签: c# asp.net .net dll nrules

以前我使用此调用来加载从Rule class

扩展的所有cs文件
var repository = new RuleRepository();
repository.Load(x => x.From(typeof(Rule1).Assembly));

通过调用上面显示的Load方法,所有与Rule1.cs相同类型的类文件(意味着从Rule类扩展的所有文件)都被加载到存储库内存中。 目前我已决定将所有这些.cs文件(即Rule1.cs)转换为dll并扫描包含这些dll的文件夹。我怎样才能实现这种行为? 目前我正在做这样的事情

Assembly assembly1 = Assembly.LoadFile(Server.MapPath("Rule1.dll"));
List<Assembly> asmblyList = new List<Assembly>();
asmblyList.Add(assembly1);
repository.Load(x => x.From(asmblyList));

我想从文件夹中扫描Rule1.dll类型的所有程序集。我怎么可能这样做?任何帮助都会很棒。

1 个答案:

答案 0 :(得分:0)

正如在上面提到的评论中,获取文件列表并加载它们不是问题,但只有一种方法可以删除已加载的程序集,这是卸载整个AppDomain。看看这个例子:

static void Main(string[] args)
{
    var path = AssemblyDirectory + @"\external\";
    var files = Directory.GetFiles(path); //get all files

    var ad = AppDomain.CreateDomain("ProbingDomain"); //create another AppDomain
    var tunnel = (AppDomainTunnel)
        ad.CreateInstanceAndUnwrap(typeof (AppDomainTunnel).Assembly.FullName,
        typeof (AppDomainTunnel).FullName); //create tunnel

    var valid = tunnel.GetValidFiles(files); //pass file paths, get valid ones back
    foreach (var file in valid)
    {
        var asm = Assembly.LoadFile(file); //load valid assembly into the main AppDomain
        //do something
    }

    AppDomain.Unload(ad); //unload probing AppDomain
}

private class AppDomainTunnel : MarshalByRefObject 
{   
    public string[] GetValidFiles(string[] files) //this will run in the probing AppDomain
    {
        var valid = new List<string>();
        foreach (var file in files)
        {
            try
            {   //try to load and search for valid types
                var asm = Assembly.LoadFile(file);
                if (asm.GetTypes().Any(x => x.IsSubclassOf(typeof (Rule1))))
                    valid.Add(file); //valid assembly found
            }
            catch (Exception)
            {
                //ignore unloadable files (non .Net, etc.)
            }
        }
        return valid.ToArray();
    }
}
//found here: http://stackoverflow.com/a/283917/4035472
public static string AssemblyDirectory
{
    get
    {
        string codeBase = Assembly.GetExecutingAssembly().CodeBase;
        UriBuilder uri = new UriBuilder(codeBase);
        string path = Uri.UnescapeDataString(uri.Path);
        return Path.GetDirectoryName(path);
    }
}