SteveDunn / Vogen

A semi-opinionated library which is a source generator and a code analyser. It Source generates Value Objects
Apache License 2.0
887 stars 46 forks source link

Swagger - MapVogenTypes not working with class libraries #691

Closed mkalinski93 closed 3 weeks ago

mkalinski93 commented 3 weeks ago

Describe the bug

I have a multi repo project that I´m working on and I was using the MapVogenTypes extension method for SwaggerGen. It seems to me, that it can only find ValueObjects in the same Assembly.

Steps to reproduce

  1. Create a plain WebApplication (.NET 8)
  2. Add Vogen via Nuget
  3. Create a simple ValubOject
  4. Use the assembly instructions with "GenerateSwashbuckleMappingExtensionMethod" and add MapVogenTypes.

This case works. Here comes the issue

  1. Create a class library
  2. Add another simple ValueObject inside the class library
  3. Reference the WebApplication project to the ClassLibrary.

MapVogenTypes will not resolve the ValueObject that remains in the Class library.

Expected behaviour

Types should have been mapped

SteveDunn commented 3 weeks ago

Thank you for the bug report @mkalinski93 . Apologies for that. I'll take a look shortly!

SteveDunn commented 3 weeks ago

Unfortunately, source generators are per-project, so it can't inspect any types found in other projects. A workaround would be to generate the same extension method in your library. But unfortunately, it writes this method without a namespace. So, without an import alias when you reference the project, you won't be able to differentiate.

To make this easier, I've made it generate the default namespace of the project. If you have types that need mapping and they're in different projects, then you'll need to change the registration:

    //opt.MapVogenTypes(); old way -for unambiguous extension method

    // when you have multiple projects with types that need mapping:
    WebApplication.VogenSwashbuckleExtensions.MapVogenTypes(opt);
    WebApplication.Shared.VogenSwashbuckleExtensions.MapVogenTypes(opt);

I've update the examples to show this too. In your library with value objects, add package Swashbuckle.AspNetCore and an assembly attribute:

[assembly: VogenDefaults(
    openApiSchemaCustomizations: OpenApiSchemaCustomizations.GenerateSwashbuckleSchemaFilter | OpenApiSchemaCustomizations.GenerateSwashbuckleMappingExtensionMethod,
    staticAbstractsGeneration: StaticAbstractsGeneration.MostCommon | StaticAbstractsGeneration.InstanceMethodsAndProperties]

This is currently in a branch and I'll release as part of the next beta soon.

Thanks again for the report

SteveDunn commented 3 weeks ago

In 5.0.5-beta3