user3048027
user3048027

Reputation: 387

How can I debug C# code from DLL in memory but no DLL in Disk

There is a c# Application that compiles C# code stored in DB and creates a DLL in memory using roslyn compiler that the DLL is loaded in memory and an instance of the type is created from the following code

   Activator.CreateInstance(type); // Just creates an instance of the type so that any public method or property can be accessed

The reason for having the code in DB is abit complex to explain here for the scope of the question but it is important to note there is no physical file where C# code is present.

Also please note the DLL is created at runtime by the application in release mode or debug mode depending if #ifdebug is true or not.

Now what we want is if the application is running in debug mode we should be able to debug the DLL created in runtime. Can experts over here help me to give pointers how to achieve it. Since access to code is there from DB we can in runtime create a temporary file in some temporary location if the application is running in debug mode but how do we let Visual studio know we want to link the specific DLL to this temporary C# file for the purpose of debugging. Please note the DLL is in memory in some concurrent bag and we arent creating PDB file too

Any pointers will be helpful We are using Visual studio 2022

Upvotes: 5

Views: 629

Answers (2)

Hank
Hank

Reputation: 2466

This is possible in Visual Studio 2022!

Follow the guidance of emitting the portable PDB from this answer. Since you didn't show much of how you are compiling, I will assume it's pretty close to that and getting the source code emitted won't be a problem.

When the assembly is finally loaded into the program, VS2022 will automatically pick up the symbols. You can verify this by looking for a your named DLL in the Modules window. Ctrl+Alt+U or Tools>Windows>Modules. From the answer I posted, it will be randomly named.

When you have the program running, the external sources node (which is new with VS2022) will show that same random DLL name.

Solution Explorer external sources node showing the generated module

If you open the generated file, you should see your generated code. You are also able to place breakpoints in this file!

The generated code with place-able breakpoints Active breakpoint being hit

Not sure if it matters or not, but in my VS options I have disabled "Just My Code".

Upvotes: 6

Ni2Be
Ni2Be

Reputation: 131

I'm not sure if this is possible with Visiual Studio but maybe you could have some luck with dnSpy: https://github.com/dnSpy/dnSpy

I was able to debug a dll that was loaded by a program at runtime using:

System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromAssemblyPath(path);

so maybe it can help you too.

Upvotes: 0

Related Questions