开发者

Using AppDomain.CreateInstanceAndUnwrap to create an instance of type T and then early binding to a method of type T

开发者 https://www.devze.com 2023-03-13 12:11 出处:网络
In the MSDN documentation for the AppDomain.CreateInstanceAndUnwrap method, it states as a note If you make an early-bound call to a method M of an object of type T1 that was returned by CreateInsta

In the MSDN documentation for the AppDomain.CreateInstanceAndUnwrap method, it states as a note

If you make an early-bound call to a method M of an object of type T1 that was returned by CreateInstanceAndUnwrap, and that method makes an early-bound call to a method of an object of type T2 in an assembly C other than the current assembly or the assembly containing T1, assembly C is loaded into the current application domain. This loading occurs even if the early-bound call to T1.M() was made in the body of a DynamicMethod, or in other dynamically generated code. If the current domain is the default domain, assembly C cannot be unloaded until the process ends. If the current domain later attempts to load assembly C, the load might fail.

(http://msdn.microsoft.com/en-us/开发者_StackOverflowlibrary/3c4f1xde.aspx)

Does anyone have a technical explanation for the above note? Why is this the case? Is Assembly dependency lookup done when a method is first called on the object?


Assembly dependency is call when you're creating instance of the object.

Let's analyze hypothetical scenario. We have 2 DLLs: Lib1 and Lib2. (Lib1 uses methods from Lib2).

In our application main method looks as below:

Worker localWorker = new Worker();
localWorker.PrintDomain();

AppDomain ad = AppDomain.CreateDomain("New domain");
Worker remoteWorker = (Worker)ad.CreateInstanceAndUnwrap("Lib1","Lib1.Worker");
remoteWorker.PrintDomain();

Assembly dependency is checking in line:

Worker remoteWorker = (Worker)ad.CreateInstanceAndUnwrap("Lib1","Lib1.Worker");

For example if the Lib2.dll doesn't exist we'll get an exception.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号