(C#) Error with building multiple target frameworks: "Cannot open 'MyApi.dll' for writing"

1.3k Views Asked by At

I am following this guide to automatically generate an API client with NSwag. But this client needs to support multiple target frameworks:

<TargetFrameworks>netcoreapp2.2;net452;net462;net472;net48</TargetFrameworks>

When I try to build this client, I get multiple errors like this:

(CS2012) Cannot open 'MyApi.dll' for writing -- 'The process cannot access the file 'MyApi.dll' because it is being used by another process.'

I suspect this is because each framework is building asynchronously and the DLL produced from my API is trying to be read by each process. How can I fix this issue / make each target framework build synchronously?

1

There are 1 best solutions below

0
On BEST ANSWER

Well, I found a solution. My lack of understanding around the guide I was reading and the build process meant I wasn't asking the right questions.

I had this build target specified in my .csproj (as directed in the guide):

<Target Name="NSwag" BeforeTargets="PrepareForBuild" Condition="'$(GenerateCode)'=='True' ">
  <Exec Command="$(NSwagExe_Core22) run nswag.json /variables:Configuration=$(Configuration)" />
</Target>

This target was running for each target framework I had specified in my <TargetFrameworks> tag. This was the task that was running in parallel to itself and causing the error from my question.

After a LOT more googling, I found this question and (consequently this answer) which gave me the solution I needed:

On multi target frameworks I use BeforeTargets="DispatchToInnerBuilds" so my custom command is only exeuted once before every build

So my final build target was as simple as this:

<Target Name="NSwag" BeforeTargets="DispatchToInnerBuilds" Condition="'$(GenerateCode)'=='True' ">
  <Exec Command="$(NSwagExe_Core22) run nswag.json /variables:Configuration=$(Configuration)" />
</Target>

It should also be noted that this solution might not work for all people looking for their build targets to run once per build. See this issue comment that provides a similar answer but with more detail about multi-project solutions.