locked
How to Unload Class Lib/ dll file ? RRS feed

  • Question

  • I have mechansim to load my dlls file as written below. I have need to know that let suppose i have a print form which call print.dll every times when it loads. If i open more than 3 forms than it means that three time i load same dll file.  will that take more resources ? or slow down my application ? .. also is their any way to unload dll file ..so that i can put a check that if dll file is already loaded than unload it and reload it again to stop loading...

    Thanks for help.

    sample code

                  var DLL = Assembly.LoadFile(Application.StartupPath +"\\dlls\\"+Asemblyname+".dll");
                    var class1Type = DLL.GetType(Asemblyname+"."+classname);
                    ISecurity security  =    Activator.CreateInstance(class1Type);

                   


    Ali Muhammad

    Friday, April 17, 2015 1:56 PM

Answers

  • With the .net CLR everything executes inside an Application Domain. Assemblies that are loaded inside the application domain can never be unloaded. The only way around this is to load a new application domain and then load your type in there and return a reference to that. Communication is then done via remoting as the instance should be a marshalbyref type and you have to unload the app domain when you are done using the type. This is unnecessarilycomplex and cumbersome given what you have to do from my interpretation of your problem.

    Instead why not use the Activator.CreateInstance overload that takes 2 strings (assembly name, type name)? Then put a try/catch block around it and load the Assembly if you get an exception? You should then only get the exception the first time that an assembly has not yet been loaded.

    Also instead of using the location of the DLLs use the probing element in the application config to automatically resolve the location of the DLL. Again I do not have enough context to know how you are needing to find these, maybe you have many many paths in a complex application, but if not use that instead of specifying the path.



    Mark as answer or vote as helpful if you find it useful | Igor

    • Proposed as answer by Kristin Xie Monday, April 20, 2015 6:06 AM
    • Marked as answer by Fred Bao Saturday, April 25, 2015 7:59 AM
    Friday, April 17, 2015 3:25 PM