load instance in a different appdomain
Is it possible to create a new app domain and instantiat开发者_JAVA技巧e an instance of a type in that new domain or can you only load assemblies into app domains? Or possibly marshal an instance reference to another app domain?
- Programming with Application Domains
AppDomain.CreateInstanceAndUnwrap
// Create a new application domain, create an instance // of Worker in the application domain, and execute code // there. AppDomain ad = AppDomain.CreateDomain("New domain"); Worker remoteWorker = (Worker) ad.CreateInstanceAndUnwrap( Assembly.GetExecutingAssembly().FullName, "Worker"); remoteWorker.PrintDomain();
You can create a new app domain and instantiate an instance of a type there. The type must be defined somewhere, but it doesn't have to be from a loaded assembly. You could marshal a serializable type to another app domain.
You are probably aware of the issues of unloading an App Domain, but if not you should look into that if you care about unloading.
I don't have my code for this handy at the moment I'm afraid.
You can do all three.
Look up MarshalByRefObject on how to invoke an object created in one domain in your current domain.
You can also specify the ApplicationBase for the automatic Assembly Lookups.
There is also the Load
method on a domain.
You have another option of using System.AppDomain.AssemblyResolve to do custom resolution. You can even stream an Assembly across the network that never existed on your machine before and have the Type resolving work with this event.
Cautions:
If your intent is to be able to unload a domain you have to make sure you do not load any Assembly or Type in your main AppDomain that you are instantiating in your child domain. This can be complicated because typically you'll want an interface between the Root AppDomain and it's children.
Yes you can:
AppDomain newDomain = AppDomain.CreateDomain("NewDomain");
newDomain.Load("MyAssembly");
There are various overloads to Load
, so check that out: http://msdn.microsoft.com/en-us/library/dwzhhcfk.aspx
精彩评论