65.9K
CodeProject is changing. Read more.
Home

Prevent code executing at Design Time in Visual Studio for Winforms Apps

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.67/5 (3 votes)

Feb 21, 2010

CPOL

1 min read

viewsIcon

9651

Either method is good for testing if you are in the designer, but another problem aside from preventing code execution, is preventing code from being jitted in the Designer. For example, you may reference assemblies or components that are dependent on native code, which cannot be loaded into any...

Either method is good for testing if you are in the designer, but another problem aside from preventing code execution, is preventing code from being jitted in the Designer. For example, you may reference assemblies or components that are dependent on native code, which cannot be loaded into any process (most likely because it may be dependent on a specific process, as one might find in a plug-in architecture or CLR host). The problem is that Visual Studio will 'jit' all code that is called from the constructor of a designable component when it is opened in the designer. This leads Visual Studio to load any assembly that contains a type that is referenced from the jit'ed code. If for some reason, a type cannot be loaded, it usually leads to a WSOD and the designable component cannot be opened in the designer. The way to stop Visual Studio from trying to load 'unloadable' code at design time, is to get that code out of the constructor or any method that's called from the constructor, and instead place it in a seperate method, and then invoke the method from the constructor via reflection. Visual Studio will jit code in any method that is called from a constructor explicitly, but will not try to jit code that is called from a constructor indirectly via reflection.