This question is closely related to an old one: Windows Form Designer: Could not load file or assembly, but the desired answer there is not given.
My problem is the following. I have a custom control that I want to use in a WinForms project in .NET. Among other things, the control requires some functionality from opencv
. So, I have an unmanaged C++ class that handles all the calls to opencv
. Let's call it Unmanaged.dll
Then, I have a C# wrapper to that that calls the unmanaged C++ using interop, let's call it CSharpWrapper.dll
. CSharpWrapper
is working and all the dependencies (Unmanaged.dll
and opencv_worldXXX.dll
) are being copied into the output directory using the <Content Include="path/to/dll"><CopyToOuputDircetory>PreserverNewest</CopyToOuputDirectory></Content>
pattern.
The ui code that is consuming CSharpWrapper
inherits from System.Windows.Forms.Control
. Let's call it MyCanvas
. When I build my application, it works perfectly (again, copying all the dependencies into the application output directory), but, when I drag and drop a MyCanvas
component from my Forms Toolbox into my form Designer using Visual Studio, Visual Studio reports a Dll not found exception on the line that builds the objects pointed to in Unmanaged.dll
.
What the answer I link above taught me is where to find the dll cache that Visual Studio populates with dependencies that are needed by Forms, Controls, Canvases etc. used by Designer. Sure enough, when I look in C:\Users\<user>\AppData\Local\Microsoft\VisualStudio\17.0_8106eeaf\ProjectAssemblies
there is a hash folder with CSharpWrapper.dll
and CSharpWrapper.pdb
in it. But none of the unmanaged dependencies are there, hence the runtime exception when using Designer. By manually copying the dependencies into that directory, Designer is satisfied and everything works.
But that is just a hack. And, worse is that, if I don't do the hack job, every time I edit my Form with MyCanvas
on it, it will regenerate the .Designer.cs file and nuke all the references to MyCanvas
. That is bad.
So, is there a way to get Visual Studio to put my unmanaged dlls into the ProjectAssemblies
cache directory automatically?
Edit:
I've tried testing for DesignMode
in the constructor for MyCanvas
so that it should skip summoning the missing Dll, but for some reason it still throws. By attaching my debugger to my project from another instance of Visual Stuio and launching the control in Designer, sure enough DesingMode
is false
. Here is the code (.NET Framework 4.8):
class MyCanvas:Control
{
private CSharpWrapper wrapper = null;
public MyCanvas() : base()
{
if(!DesignMode) // <- false when using Designer for some reason
wrapper = new CSharpWrapper(); // <- summons Unmanaged.dll here
}
}