How to load dll's during debug in VS2013

大憨熊 提交于 2021-02-18 22:34:06

问题


I have some code

var aa = a();
b(aa);

While debugging, I set a breakpoint on the b() call. Then going to the immediate window, I'd like to be able to execute code from a DLL that is in my project but is not yet loaded. Say I want a new Boo and call Foo(). The code is in the namespace Baz in dll Spongle.dll.

When I type

>> new Baz.Boo().Foo(aa)

I get the error: The type or namespace name 'Baz' is not valid in this scope.

If I change my code such that my Boo is already loaded it works fine.

new Boo(); // dummy to ensure loading
var aa = a();
b(aa);

Is it possible to load the dll from the immediate window during debug so I can call my code despite it being loaded (yet)?. I could use the new Boo() as a static initializer of my application main class, but then I have problems during unit testing as it won't necesarily involve the class with that static initializer.


回答1:


Although heavy, you can of course use reflection to load the assembly for that test.

The following would not work:

var obj = new Newtonsoft.Json.Linq.JObject();

since the assembly isn't yet present. However, if I explicitly load it first via reflection and an absolute path to my bin, I can instantiate the object just fine.

var assembly = System.Reflection.Assembly.LoadFile("C:\\AbsolutePath\\bin\\Debug\\Newtonsoft.Json.dll");
var obj = new Newtonsoft.Json.Linq.JObject();

The reason for this necessity from the Immediate Window is that as your application (or unit test boostrapped application in this case) loads, it looks for references throughout the code and loads the required assemblies to satisfy your needs. In your case, you don't have an explicit reference to the assembly in your code, so it isn't loaded. The immediate window has no context and, as such, you have to explicitly load it.

To programatically reference potential assemblies to load, you can use the bin directory of the loaded assembly. This allows you to pull the absolute path at runtime.

var filePath = new Uri(this.GetType().Assembly.CodeBase).LocalPath;
var bin = System.IO.Path.GetDirectoryName(filePath);
var assembly = System.Reflection.Assembly.LoadFile(bin + "\\Newtonsoft.Json.dll");


来源:https://stackoverflow.com/questions/29834206/how-to-load-dlls-during-debug-in-vs2013

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