ObjectMapper icon indicating copy to clipboard operation
ObjectMapper copied to clipboard

Generate at compile time

Open waxingsatirical opened this issue 4 years ago • 3 comments

Hi, I implemented something similar to ObjectMapper in one of my projects, but in a very slapdash way using powershell and reflection. I had the generation happening at compile time, with a build event to kick off the powershell scripts.

Is there a reason why you opted to make the generation a manual step? Do you have your generated code committed to source control?

waxingsatirical avatar Mar 11 '21 10:03 waxingsatirical

This was low effort implementation to generate boilerplate code. My goals were:

  • No runtime reflection (what AutoMapper was doing), since you don't know if it will work until you run it
  • Compile time safety (if somebody renamed, removed property, fail on build)
  • Works with refactoring tools
  • If I have use case which is not covered by the tool, I can update code manually
  • Simple to integrate and use in different projects (this is why I didn't want to plug into MSBuild)

Because of that I opted to use analyzers with explicit action to generate boilerplate code (similar to other refactorings). Code is committed to repo and you can modify it however you like. Today I would maybe look into source code generation (since this is build on same stack as analyzers, it is just automatic), but in this case I would not be able to achieve goal n4. It depends on what you want to achieve.

nejcskofic avatar Mar 12 '21 08:03 nejcskofic

What do you mean by "source code generation" is this a specific tool? I'd like to look into it. You make a good point about being dependent upon MSBuild, that's is a major downside of the compile-time generation I had hooked up. Got any ideas of a cross-platform way to do it?

waxingsatirical avatar Mar 12 '21 11:03 waxingsatirical

Source code generator is a new feature in .net5 compiler (you need .net5 compiler though generated code can target anything that compiler can target). It may be something you might be able to utilize or not, depending on platforms you are developing for. Couple of links:

This will also be the most simple and cross platform option, since it is integrated directly into toolchain Microsoft provides. I believe integration is done directly inside compiler, so no MSBuild custom steps.

Disclaimer: While I know about the feature and I have read about it, I haven't tried it on concrete use case. I'm not doing much of the .net development anymore.

nejcskofic avatar Mar 14 '21 12:03 nejcskofic