dotnet / dotnet/msbuild

Correct way to generate sources for an external project (with incompatible `TargetFramework`)?

Open
#10,169 0 comments 0 reactions 1 assignee Claimed by @MichalPavlik View on GitHub
question
Dominant language
C#
Stars
5.5k
Forks
1.5k
Avg merge
1d 8h
Merged PRs (30d)
141

Description

I have the following project structure:

**Project A**
- Generates a JSON file on `AfterTargets="PostBuildEvent"`

**Project B**
- References project A via `ProjectReference` to ensure correct build order
- Consumes the JSON file inside `AfterTargets="AfterResolveReferences" BeforeTargets="CoreCompile"` and generates source code.

This seems to work. However it requires the `TargetFramework` of project A to be compatible with project B, even though **project B does not rely on any of its code**. There are a bunch of issues addressing this problem (See https://github.com/dotnet/msbuild/issues/2661 or https://github.com/dotnet/msbuild/issues/4795), but none of the workarounds described there seem to work.
I am generally wondering if there's some kind of "best practice" for dealing with this code generation scenario?

EDIT: I just found this [blog post](https://jaylee.org/archive/2019/01/25/create-a-buildreference-dependency-between-sdk-style-projects.html) which uses `TargetFramework`. It seems to fix the incompatible `TargetFramework` issue, but it somehow breaks the `AfterResolveReferences` target. It's called multiple times now for some reason.

EDIT2: After some more testing I made the hack above work. The problem is using multiple `TargetFrameworks` in the referencing project. Targeting just one framework and including the referenced project with `true` seems to do the trick. So for anybody struggling with this in the future:

```xml

netstandard2.1

...




false
true

```

This calls a source generator **after** the referenced project is built and includes generated sources in the compilation. It also works if the referenced project targets a different `TargetFramework`. I still have no idea if that's the best way to do it though. So would be nice if someone more knowledgeable than me could chime in.

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.