Loading DLLs into a separate AppDomain

僤鯓⒐⒋嵵緔 提交于 2019-11-26 14:35:28

More specifically

AppDomain domain = AppDomain.CreateDomain("New domain name");
//Do other things to the domain like set the security policy

string pathToDll = @"C:\myDll.dll"; //Full path to dll you want to load
Type t = typeof(TypeIWantToLoad);
TypeIWantToLoad myObject = (TypeIWantToLoad)domain.CreateInstanceFromAndUnwrap(pathToDll, t.FullName);

If all that goes properly (no exceptions thrown) you now have an instance of TypeIWantToLoad loaded into your new domain. The instance you have is actually a proxy (since the actual object is in the new domain) but you can use it just like your normal object.

Note: As far as I know TypeIWantToLoad has to inherit from MarshalByRefObject.

If you're targeting 3.5, you can take advantage of the new managed extensibility framework to handle all the heavy lifting for you.

You can use the AppDomain.CreateInstance method to do this. You'll need to call the Unwrap method of the ObjectHandle that is returned to get at the actual object.

Create a new Appdomain with AppDomain.Create( ... ). After creating the AppDomain load the DLLs into that AppDomain.

Look into all the methods that Appdomain has with Create*. There are certain things like CreateInstanceAndUnwrap, etc.

As previously stated, use AppDomain.CreateDomain to create a new app domain. You can then load an assembly into it using the Load method, or even execute an assembly using the ExecuteAssembly method. You can use GetAssemblies to see if an assembly has already been loaded. Be aware too that you cannot unload an assembly once it's loaded. You will need to unload the domain.

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