Reputation: 143
I have an assembly called Lab that is built by a project that is part of a solution. This assembly contains an object that I want to access using reflection from a different assembly on the same solution. In the other assembly (Called BL) I have the following code:
Assembly assembly = Assembly.Load("Lab");
The problem is, that it is throwing FileNotFoundException
unless I add a row that tries to initiate an object from the Lab assembly anywhere in the code.
As if the compiler loads the Lab assembly to a recognisable place for the Assembly.Load
function.
This really confuses me,
I tried passing the full assembly name
And also tried to pass the assembly's absolute path to Assembly.LoadFrom
but to no avail, same problem in all cases.
The reason I am trying to access the object trough reflection rather than just referencing to it is because the code is part of a module that will be isolated. And then the reflected dll (in this case Lab.dll) will be passed dynamically during runtime.
Solution
Indeed as Avner explained and I suspected, the assembly wasn't copied to the project's folder because there was no code that uses it. What further proves that the assembly was missing is the FusionLog of the exception thrown as noted by Lordkain in the comments.
Because the idea of the project is to use a passed Assembly Path in the future, I just resorted to implement that part right now as opposed to the solutions suggested by Avner. So by using the assembly's path instead of the assembly's name with the method:
Assembly.LoadFrom(*Assembly Path*);
I worked around the missing assembly problem.
Upvotes: 1
Views: 3210
Reputation: 14700
Check out the BL project's output folder. Chances are, you won't find Lab.dll there. That's because Visual Studio occasionally tries to be helpful, sees that there's no recognizable code that uses Lab.dll, and doesn't bother actually copying it to the output folder. When you code uses reflection, static analysis fails to find any usages, and it optimizes away the reference.
This answer addresses this problem, though from a different angle:
MSBuild doesn't copy references (DLL files) if using project dependencies in solution
Since in your case you're not having a problem with second-hand references, but with dynamic loading, so option #1 is irrelevant, and you'll probably have to settle for referencing (note: referencing, not necessarily instantiating) an item from Lab.dll.
You can do it by getting the Type of an object from Lab.dll, like the linked answer shows, or accessing a Static property on a class, if you have one. Ugly, but effective.
Upvotes: 1