6

Possible Duplicate:
Loading DLLs into a separate AppDomain

What is the proper way to load a .NET assembly into a separate AppDomain so you can have access to its Types/Classes but still be able to unload it (and reload it).

This is a tangent of this previous discussion: C# - Correct Way to Load Assembly, Find Class and Call Run() Method

Community
  • 1
  • 1
BuddyJoe
  • 69,735
  • 114
  • 291
  • 466

1 Answers1

3

Basically, you just create the new AppDomain, and then call AppDomain.CreateInstanceAndUnwrap to create the type. Here's a simple CodeProject article about this process.

There are some tricks, here. You can't ever refer to the Type directly (this will load the type into your current AppDomain), and the objects should all derive from MarshallByRefObj. This will allow you to use the object "remotely", meaning keep it from loading into your AppDomain.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • +1 thanks. How bad is the performance penalty each time you cross AppDomains? – BuddyJoe Aug 04 '09 at 17:08
  • 1
    It depends. Anything passing between teh appdomains is basically serialized across. (It works very similarly to Remoting.) In general, if all of your types derive from MarshallByRefObj, they will only serialize a "handle" across, so it's quite fast. When you read the data, the data will be serialized, though, which can slow things down a bit. Try to always keep as much "internal" in the second appdomain, and it probably wont' be an issue. – Reed Copsey Aug 04 '09 at 17:12
  • Note also that remote instance life time is limited. Depending on .Net version, you should use WCF instead of remoting. – Guillaume Jul 05 '11 at 08:57
  • @Guillaume How does that apply? Cross AppDomain is inherently done with Remoting. – David Pfeffer Feb 26 '12 at 21:26
  • http://msdn.microsoft.com/library/72x4h507.aspx Remoting is deprecated. Nothing prevents you from using WCF between two AppDomain. – Guillaume Feb 28 '12 at 14:51
  • @Guillaume remoting is not recommended for IPC Communication, it is not depcrecated for app domain communication – ilansch Sep 17 '14 at 11:21
  • @ilansch You are right, remoting is not deprecated but legacy and WCF is recommended (also for app domain). http://stackoverflow.com/questions/1294494/is-net-remoting-really-deprecated – Guillaume Sep 17 '14 at 12:33
  • I will add this link http://www.brad-smith.info/blog/archives/500 It was very helpful to me ! – ilansch Sep 17 '14 at 12:59