.NET Load assemblies at runtime Again

I posted a similar question a time ago. I need to load an assembly at runtime.

This is easy if I know the absolute path of the dll at runtime.

But I dont :( The assembly.Load() or LoadFromFile() fails if the file is not in the application root.

The only thing I have is the dll name. The dll could be located in the root, system32 or in even in the GAC.

Is it possible for .net to automatically determine where the dll is at, like for example : it should first look in the root. If its not there move on to the system folders, else try the GAC.

EDITED

I am using plug-in architecture. I do not need to register the dll. I have a multi user application. I have a applications table containing information regarding applications. Each application has a dll path associated with it, containing certain algorithms associated with that app. Hope this helps.


When the current application looks for assemblies, it looks in several locations (bin folder, gac, etc..) if it can not find one, then the developer needs to manually tell the application where to look. You can do this by intercepting the AssemblyResolve event, and using the event args to tell the CLR where your assembly is.

AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
....................
Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
   var strTempAssmbPath=
          Path.GetFullPath("C:WindowsSystem32" + args.Name.Substring(0,  args.Name.IndexOf(",")) + ".dll");

   var strTempAssmbPath2=
          Path.GetFullPath("C:Windows" + args.Name.Substring(0,  args.Name.IndexOf(",")) + ".dll");


    if (File.Exists(strTempAssmbPath))
            return Assembly.LoadFrom(strTempAssmbPath);

    if (File.Exists(strTempAssmbPath2))
            return Assembly.LoadFrom(strTempAssmbPath2);
}

您可以连接到AppDomain.CurrentDomain.AssemblyResolve事件并根据需要手动加载应用程序的程序集。


Yes there is a way and it depends on whether your dll is weakly(without a public key token) or strongly(with a public key token) named. If its weakly named and you have added a reference to the assembly with the dll within VS, then VS will first look in the application folder root and if it does not find it, it will then look in the subdirectories that you specify as the value of the privatePath attribute in your XML config file.

If its a strongly named dll, then the CLR will search in the GAC so you need to install the dll in the GAC. The CLR can also look in the application directory if you install an XML config file that has its codeBase element pointing to the dll's path.

To specify an assembly in the GAC you can use the /reference:[DLL name] switch when compiling your assembly.

链接地址: http://www.djcxy.com/p/44436.html

上一篇: .NET中的程序集位于物理位置?

下一篇: .NET在运行时加载程序集再次