Can I tell my application to load all assemblies (DLLs) from a specific location?

可紊 提交于 2019-12-02 11:33:28

Yes, shared files (if for some reason you do not want to put them in GAC) can be deployed, for example, in the Common Programs folder.

According to the way your application works you may need to load them explictly with Assembly.LoadFrom() using the path you get from Environment.GetSpecialFolder() for Environment.SpecialFolders.CommonPrograms or attaching and event handler for AppDomain.AssemblyResolve event.

Let's see a raw and simple example:

// Put this in your initialization code
public static void Main()
{
    AppDomain.CurrentDomain.AssemblyResolve += new ResolveAssembly(MyResolveEventHandler);
}

private static Assembly ResolveAssembly(object sender, ResolveEventArgs e)
{
    // Clean, check, double check and verify path name to be sure it's a valid
    // assembly name and it's not a relative path itself, you may even check e.RequestingAssembly
    string path = ...; 

    return Assembly.LoadFrom(path);
}

If you have the directory and you want to load them all at startup (just in case...):

private static LoadThemAll(folderPath)
{
    foreach (var path in Directory.GetFiles(folderPath, "*.dll"))
        Assembly.LoadFrom(path);
}

Do not forget to add proper error handling (for non managed DLLs, wrong versions and everything else may happen, especially because that assemblies will be loaded in your AppDomain and everyone may put a malicious one in that folder).

Of course all of these can be applied to any (accessible) folder, which one is the best...well it depends on what you're trying to load and how it's deployed (you can even search in Registry to dynamically find where support files are located).

Finally in case assemblies you referenced are strong signed and they reside on a known, fixed, immutable location you can use <codebase> in your .config file.

We have used the probing path in asp.net applications to do something similar in the past:

http://msdn.microsoft.com/en-us/library/823z9h8w.aspx

Has a side affect in asp.net where the assemblies in these locations will not be loaded automatically when the application runs, only when they cannot be found in bin.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!