简体   繁体   中英

Is it possible to exclude auto-generated files when importing classes from one C# project to another?

Is it possible to exclude auto-generated files when importing classes from one C# project to another?

I have one project that implements a GRPC service based on classes generated from the proto file.

Also, I have another project where I test classes of the first project like GRPC service. In the second project, I implemented a GRPC client to test the GRPC service with the same copy of the proto file.

The problem is that I import all classes of the first project and sorrowfully some of them are generated with the same proto file and there are a lot of warnings about class names collisions.

Is there a way to import only specific files between projects of the same solution?

I use the next directives in project files to generate classes:

  • In the first project:
<ItemGroup>
    <Protobuf Include="Protos\Proto.proto" GrpcServices="Server" />
</ItemGroup>
  • In the second one:
<ItemGroup>
    <Protobuf Include="Protos\Proto.proto" GrpcServices="Client" />
</ItemGroup>

And I import classes of the first project to the second one like this:

<ItemGroup>
    <ProjectReference Include="..\core\First.csproj" />
</ItemGroup>

And the warnings are like this:

TestClient.cs(53,29): warning CS0436: The type 'Type1' in '/folder1/solution/test_project/obj/Debug/netcoreapp3.1/Class1.cs' conflicts with the imported type 'Type1' in 'Project1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in '/folder1/solutiion/test/obj/Debug/netcoreapp3.1/Class1.cs'. [/folder1/solution/test_project/Project2.csproj]

I usually create my proto files and their resulting generated code in a single assembly, then reference that assembly from the service and the client assemblies. This keeps the code generated once, and eliminates the duplicated code generation.

You can't conditionally import the types, but you can add an extern alias to the types in your First project when importing it to the second project.

Add the following snippet to your second .csproj

  <Target Name="ChangeAliasesOfStrongNameAssemblies" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences">
    <ItemGroup>
      <ReferencePath Condition="'%(FileName)' == 'First'">
        <Aliases>FirstExtern</Aliases>
      </ReferencePath>
    </ItemGroup>
  </Target>

you can now explicitly define which type you want to use: add this above all the usings in your .cs code:

extern alias FirstExtern;

and reference the types from the first project by specifying the defined alias:

FirstExtern::First.Type1 variable;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM