Skip to content

feat: Generate mappers as free-standing classes in their own assembly - #443

Draft
kevin-mcmanus wants to merge 7 commits into
Tim-Maes:masterfrom
kevin-mcmanus:feature/facet-mapper
Draft

kevin-mcmanus wants to merge 7 commits into
Tim-Maes:masterfrom
kevin-mcmanus:feature/facet-mapper

Conversation

@kevin-mcmanus

Copy link
Copy Markdown

This is the second half of what #143 asks for. The contract-assembly PR (#442) keeps the source layer out of the compiled contract assembly by removing the generated mapping; this one puts the mapping back, in an assembly that is allowed to see both layers. Please refer to the issue for the background and motivation.

I built this before I found #389, which covers the same ground. It's a draft for that reason — see Relation to #389 below. I'm not proposing a second cross-assembly mapping attribute, and I'd rather fold what's useful here into [FacetMap] than have both.

The diff is larger than this PR. It sits on the contract-assembly and shared-helpers PRs, which are not merged yet, and a PR's base has to be a branch in this repository — so their commits ride along. Only the last four are this PR's own work:

5de74e5 the shared-helpers PR
63b1170 the contract-assembly PR
dce33aa merge of the two
0b8943e this PR the mapper generator and its hooks
a4adaed this PR the manifest, so a whole contract assembly registers in one line
18a55f9 this PR ApplyTo, the reverse mapping that preserves identity
01478be this PR docs and a runnable four-project sample

Happy to rebase onto master once the other two are merged, which shrinks the diff to those four.

The idea

[Facet] generates the mapping as more members of the facet type, so it can only be generated where that type is — and it has to name the source type, which a contract assembly mustn't reference. The mapping becomes a separate type instead: a static class, generated in a second assembly that references both sides and runs the generator itself. It reads the facet from metadata like any other referenced type, so each generator still only writes into its own compilation.

[assembly: FacetMapper(typeof(UserUseCaseModel), typeof(UserResponse))]
public static class UserResponseMapper
{
    public static Expression<Func<UserUseCaseModel, UserResponse>> Projection { get; }
    public static UserResponse ToUserResponse(this UserUseCaseModel source);
    public static UserResponse ToUserResponse(this UserUseCaseModel source,
        IFacetMapConfigurationInstance<UserUseCaseModel, UserResponse> configuration);
    public static IQueryable<UserResponse> SelectUserResponse(this IQueryable<UserUseCaseModel> source);
    public static UserUseCaseModel ToUserUseCaseModel(this UserResponse facet);
    public static UserUseCaseModel ApplyTo(this UserResponse facet, UserUseCaseModel target);
}

It rests on one property of Facet's existing output: generated members are settable and the projection is an object initializer, which is legal inside an expression tree. So the same initializer text serves both the runtime mapper and Projection.

EF Core still translates it

The thing I was most careful not to break. A rule declared through ConfigureProjection is folded into the projection's bindings rather than applied after it, so the provider sees one object initializer:

SELECT "u"."Id", "u"."Name", ..., "u"."Name" || ' #' || CAST("u"."Id" AS TEXT)
FROM "Users" AS "u"
LEFT JOIN "OrderUseCaseModel" AS "o" ON "u"."Id" = "o"."UserUseCaseModelId"
WHERE "u"."Id" = 7

One statement, joins included, no client-side evaluation. Nested registrations inline for the same reason.

Hooks

Which path each reaches is forced by what an expression tree can hold. IFacetMapConfiguration.Map is imperative, so it runs in To{Facet} only. IFacetProjectionMapConfiguration.ConfigureProjection declares expressions, so one declaration covers both Projection and To{Facet}. Applying those rules at runtime compiles a tree, so that method is [RequiresDynamicCode], matching how Facet.Extensions annotates its dynamic-code paths; Projection only builds a tree and needs none.

The configuration type lives in the mapper assembly, so it can name source and facet in one signature — [Facet]'s Configuration has to sit where the facet is, which in a layered build is the one place that can see neither.

Registering once instead of twice

Naming each pair as both a [Facet] and an [assembly: FacetMapper] is two places to keep in step, and forgetting the second is silent — a contract facet has no mapping members of its own to go missing. So a facet assembly records its own pairs:

[assembly: AssemblyMetadata("Facet.Contract.ApiModels.UserResponse", "AppLayer.UserUseCaseModel")]

Two strings, naming no types, so the record survives Facet_EmitAttributeMetadata=false — which is the difficulty, since that setting strips the very attributes a reader would otherwise enumerate. One line then registers everything:

[assembly: FacetMappersForAssembly(typeof(UserResponse))]

FAC115 reports what's left uncovered, but only in an assembly already mapping from that contract assembly — so ordinary Facet use never hears from it.

Mapping back

GenerateToSource emits two methods, and the difference is identity. To{Source} constructs, so it carries only the flat members: a nested child would have to be a new object, which an ORM reads as an insert with the previous child orphaned. FAC118 (info) lists what was left out.

ApplyTo writes onto an instance you already have:

var tracked = db.Users.Single(u => u.Id == id);
response.ApplyTo(tracked);
db.SaveChanges();

Nested members are updated in place where the target has one, so the child keeps its identity. Where it's null it stays null — creating it is a decision about the aggregate. Collections are never reconciled; what an added or removed element means needs a key and a policy. ApplyTo constructs nothing, so it's generated even where To{Source} can't be.

Two limits

Members are matched by name. The facet is read from metadata, where its own [Facet]/[MapFrom] attributes need not be present — depending on them would fail for exactly the assemblies this exists to serve. So MapFrom, MapWhen and ConvertEnumsTo don't reach the mapper; a Configuration covers what the name match can't, and FAC110 reports each property left unfilled.

FAC114 covers the real constraint. Roslyn runs every generator against the same input compilation, so none sees another's output: a [Facet] type in the same compilation as its registration appears to have only its hand-written members, so the mapper is generated from those alone. FAC114 is a warning and says how many were mapped, which is what makes the case
diagnosable. Not a restriction in practice — a facet in its own assembly can carry its own mappings.

Relation to #389

[FacetMap] generates the same shape — extension methods plus an Expression projection, in a project that references both sides. The difference isn't in the generator, it's in where the target comes from: a hand-written POCO there, a [Facet]-generated type read from metadata here. That's a source difference, so one generator could serve both.

What this has that #389 doesn't:

  • Auto-registration from a manifest. With [FacetMap] each pair is named twice — once where the DTO is defined, once on the marker class — and the second is easy to forget. Here the facet assembly records its own pairs as AssemblyMetadata strings, and one attribute registers all of them.
  • Diagnostics. Seven of them. The one I'd most want in [FacetMap] is for a target property that matched nothing on the source: it's skipped silently, and with a hand-written target that drift is only a matter of time. The other is the same-compilation case under Two limits. I tried it against [FacetMap]: FacetMapModelBuilder returns null when no member matches, so no file is emitted, the marker class stays empty and the call site is a CS0117 with nothing saying why. A broken build rather than a wrong mapping, so less dangerous than I'd assumed — but still a puzzle to land on.
  • ApplyTo keeps a nested child's identity. [FacetMap]'s ApplyTo{Source} assigns a freshly mapped child onto the target, so the previous instance is replaced; ours writes onto the instance already there. For a tracked entity that's the difference between an update and an insert with the old child orphaned. (Checked on your branch with a nested Address.)
  • Reuse of the existing collection table. I started with my own and it covered seven shapes where WrapCollectionProjection covers eighteen, so ImmutableSortedSet<T> and IImmutableQueue<T> members that [Facet] handles fell through. That's why the shared-helpers PR exists.

What #389 has that this doesn't: SelectFacet<TOut>() discovery, MaxDepth and CollectionTargetType.

So the ask here is a steer rather than a merge. Folding the four above into [FacetMap], as a mode where the target is a generated facet, looks like the smaller and better change, and I'm happy to do it on your branch. If you'd rather keep them separate, this stands on its own.

Sample

samples/LayeredArchitecture — four projects, with the host printing its contract assembly's references.

It references the Facet projects directly, so it builds with the repository: open the solution, set Api.Host as startup, F5. Those projects are in the sample solution because Visual Studio restores at solution scope and a ProjectReference outside it fails with NU1105.

Final notes

44 files are this PR's own work, with 2 new test files and 2 modified. The suite passes, with no new warnings.

Checklist

  • I read the contributing guide and followed the code of conduct.
  • I added or updated tests when behavior changed.
  • I updated documentation, samples, or release notes when needed.
  • I ran dotnet test locally.
  • My change is ready for review.

kevin-mcmanus and others added 7 commits October 8, 2026 15:49
Two helpers existed in several copies across the generators.

The auto-generated file header had four implementations (facet, flatten,
wrapper, GenerateDtos). They were not identical: each named its own
generator, GenerateDtos carried no version and appended #nullable enable,
and flatten read the assembly version by reflection rather than through
FacetConstants. So the shared helper takes the generator name and whether
to include a version, and each call site keeps its exact previous text.

WrapCollectionProjection — which maps a collection shape to its
materialising call, and is the single place that decides which collection
types are supported — was private to ExpressionBuilder. It moves to
GeneratorUtilities, with ExpressionBuilder delegating to it.

No behaviour change. Verified by emitting every generated file for
Facet.Tests before and after: 823 files, byte-for-byte identical.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
A facet in a contract or domain project drags that project's dependency
on the source layer into the compiled output, which is what makes Facet
awkward in a layered solution (Tim-Maes#143). Three separate things do it: the
typeof inside [Facet], the generated mapping members that name the source
type, and nested property types copied across as the source's own.

Two properties close the first two:

  Facet_GenerateMappings=false      omits the *.Mappings.g.cs half
  Facet_EmitAttributeMetadata=false keeps Facet's attributes, and so the
                                    typeof inside them, out of metadata

The attributes are now [Conditional(FACET_KEEP_ATTRIBUTES)]. The
generator reads them from the semantic model either way, so generation is
unaffected; only the emitted blob changes, and the compiler then elides
the references that only those arguments were keeping alive.
Facet.Attributes.targets defines the symbol by default, so every existing
project is unchanged — and it lives in that package rather than in Facet
because the [Conditional] is on a type there: a project referencing the
attributes without the generator would otherwise lose its attributes with
no targets file through which to ask for them back.

NestedFacets already closes the third, but silently. Two new diagnostics
cover the ways this quietly fails, both only where the project has
declared its facets to be contracts:

  FAC116  a generated property still typed from the source layer
  FAC117  a mapping hook that cannot run, because the members that would
          call it are the suppressed ones

Facet.Tests.ExternalLib doubles as a contract assembly so the claim is
tested rather than argued: ContractAssemblyReferenceTests reads the
emitted metadata and asserts no source-typed constructor, no Projection,
no FromSource and no Facet.Attributes reference.

Verified end to end through the built package: a contract project whose
facets include a nested one compiles to an assembly whose only reference
is System.Runtime.

This removes the mapping rather than relocating it — a partial type cannot
span assemblies, so the mapping has to be something free-standing, in a
project that references both layers. Facet's facets suit that already:
their members are settable and the projection is an object initializer.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
…apper]

[Facet] emits its mapping members as a partial half of the facet type, so
they can only ever land in the assembly that declares the facet — and
they name the source type, which is what drags that layer into a contract
assembly's metadata. A C# partial type cannot span assemblies, so the
mapping cannot simply be moved: it has to be a different shape.

A static class of extension methods has no such constraint, and is driven
from the assembly that is allowed to see both layers:

  [assembly: FacetMapper(typeof(UserUseCaseModel), typeof(UserResponse))]

Emits Projection, To{Facet}, Select{Facet} and optionally To{Source},
plus the hooks: Configuration, BeforeMapConfiguration,
AfterMapConfiguration and ToSourceConfiguration, reusing the Facet.Mapping
interfaces rather than inventing any.

The split between the two mapping paths is forced rather than chosen.
IFacetMapConfiguration.Map is imperative, so it can only run in the
method. IFacetProjectionMapConfiguration declares its rules as
expressions, so they are merged into Projection's object initializer —
folded into the bindings rather than applied afterwards, because calling
anything on the result is what makes a query fall back to loading rows
and mapping them in memory. The same rules are compiled to assignments
for the method path, so one declaration serves both; that method carries
[RequiresDynamicCode] accordingly, following how Facet.Extensions
annotates its own dynamic-code paths. Projection itself only builds an
expression tree and needs no such annotation.

Members are matched by name, because the facet is read from metadata
where its own [Facet]/[MapFrom] attributes need not be present — a mapper
that depended on them would stop working for exactly the assemblies this
exists to serve. FAC110 reports each property that could not be filled,
so a rename on either side is a build warning rather than a silently
defaulted value.

Nested facets and collections of them are inlined where their own pair is
registered, keeping the whole graph one translatable expression. The
collection shapes accepted are whatever [Facet] accepts, because both now
go through GeneratorUtilities.WrapCollectionProjection.

FAC111-FAC114 cover the registrations that cannot work: an uninstantiable
facet, a source with no parameterless constructor under GenerateToSource,
two mappers that would share a class name, and — the one worth
singling out — a facet declared in the same compilation as its
registration. Roslyn runs every generator against the same input, so one
generator never sees another's output: such a facet appears to have only
its hand-written members, and the mapper would silently map nothing.

Facet.Tests.ExternalLib gains contracts for its two existing entities so
the tests can cover an exclusion and a reverse mapping without inventing
more source types.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
[assembly: FacetMapper] names one pair, which means each pair is written
down twice: once as the [Facet] in the contract assembly, once as the
registration in the mappers assembly. Two places to keep in step is one
too many, and forgetting the second is silent — a contract facet has no
mapping members of its own to go missing, so nothing complains until
something calls a method that was never generated.

A facet assembly now records its own pairs:

  [assembly: AssemblyMetadata("Facet.Contract.ApiModels.UserResponse",
                              "AppLayer.UserUseCaseModel")]

Two strings, naming no types, so the record survives an assembly built
with Facet_EmitAttributeMetadata=false — which is the whole difficulty:
that setting is exactly what strips the [Facet] attributes a downstream
reader would otherwise have enumerated. AssemblyMetadataAttribute is in
the framework every project already references, so this costs no
dependency of any kind, and Roslyn reads assembly attributes off a
referenced assembly without trouble.

One line then registers the lot:

  [assembly: FacetMappersForAssembly(typeof(UserResponse))]

An explicit registration for a pair still wins, which is how a single
facet gets its own Name, Exclude or Configuration while the rest are
covered wholesale.

FAC115 reports what is left over, and only in an assembly that already
maps something from that same contract assembly. A project using Facet
the ordinary way has no registrations and hears nothing; so does one that
merely references a contract assembly it has no mappers for. The
diagnostic therefore means drift in a set of mappers somebody is
maintaining, rather than "you could write more mappers".

FAC117's message now points at the Configuration on [assembly: FacetMapper]
again. It was deliberately vaguer when contract mode landed on its own,
because that API did not exist yet.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
GenerateToSource emitted one reverse mapping, To{Source}, which
constructs. That limits it to the flat members: a nested child would have
to be a brand-new object, which an ORM reads as an insert with the child
that was there before left an orphan. So nested members were skipped —
and silently, documented only in the generated XML nobody reads.

Both halves of that are addressed.

ApplyTo writes the mapped members onto a source instance the caller
already has:

  var tracked = db.Users.Single(u => u.Id == id);
  response.ApplyTo(tracked);
  db.SaveChanges();

A nested member is updated in place wherever the target already has one,
so the child keeps its identity and whatever was tracking it still is.
Where the target's child is null it stays null: creating it is a decision
about the aggregate, not about mapping. Collections are not touched at
all, because reconciling one needs a key and a policy for added and
removed elements that only the application can supply.
ToSourceConfiguration runs last in both directions.

Because ApplyTo constructs nothing it needs no parameterless constructor
on the source type, so it is generated even where To{Source} cannot be —
which makes FAC112 an omission of one method rather than of the whole
reverse direction, and its message now says so.

FAC118 (info) lists what the reverse mapping leaves at its defaults and
why each member is excluded. The forward direction has reported its
unmapped members as FAC110 from the start; this is the same statement for
the other direction. The definition of "what cannot be carried back" now
lives once on the registration and is shared by the emitter and the
diagnostic, so they cannot disagree.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Four projects demonstrating the whole arrangement: an application layer,
a contract assembly shaped from it, a mappers assembly that is the only
one seeing both, and a host standing in for a web API.

The host proves the result rather than asserting it. Section 4 reads its
own Api.Contracts.dll metadata and prints the assembly references, which
come out as System.Runtime and System.Collections — the latter being
List<T>. Section 2 prints the SQL for a projection, including a custom
rule declared through ConfigureProjection, so the claim that a hook
survives into the query is visible rather than described. Sections 1 and
3 print the in-memory mapping and both reverse directions, where ToSource
leaves the nested members alone and ApplyTo updates them in place.

It consumes Facet by ProjectReference, so it builds with the repository
and needs no packing step. Two consequences of that, both noted in the
README and in the files themselves:

  - Facet's own three projects are in LayeredArchitecture.slnx, grouped
    under a folder named for the purpose. They have to be: Visual Studio
    restores at solution scope, so a ProjectReference to a project
    outside the solution fails with NU1105. The command line does a full
    graph restore and does not notice, so this only shows up in the IDE.
  - Facet.props and Facet.targets are imported by hand in the two project
    files that need them, because a PackageReference imports them for you
    and a ProjectReference does not. Each import says so, which keeps the
    rest of those files to the properties a real consumer writes.

The sample deliberately does not set CopyAttributes. The application
layer carries EF Core attributes on purpose, to show they stay where they
are, and copying them is a separate subject with its own mode.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@kevin-mcmanus kevin-mcmanus changed the title Generate mappers as free-standing classes in their own assembly feat: Generate mappers as free-standing classes in their own assembly Oct 12, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant