Используйте SourceGenerator с зависимостями в одном решении.C#

Место общения программистов C#
Anonymous
Используйте SourceGenerator с зависимостями в одном решении.

Сообщение Anonymous »

Привет, я пытаюсь написать SourceGenerator, использующий пакет Humanizer (этот пакет необходим только при создании кода и не должен добавляться в качестве ссылки в проект, использующий SourceGenerator)
Итак, у меня есть следующие файлы:
TestSourceGenerator\TestSourceGenerator.csproj

Код: Выделить всё


netstandard2.0
latest
enable
false
true
enable
$(TargetsForTfmSpecificContentInPackage);_AddAnalyzersToOutput
true

















TestSourceGenerator\SourceGenerator.cs

Код: Выделить всё

using System.Text;
using Humanizer;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;

namespace TestSourceGenerator;

[Generator]
public class SourceGenerator : ISourceGenerator
{
public void Execute(GeneratorExecutionContext context)
{

var builder = new StringBuilder(1024);

builder.AppendLine(@$"using System;
namespace {context.Compilation.Assembly.ContainingNamespace?.Name ?? context.Compilation.Assembly.Name};
static class AssemblyInformation {{
public static string Name = ""{context.Compilation.AssemblyName}"";
public static string HumanizedName = ""{context.Compilation.AssemblyName.Humanize()}"";
}}
");

context.AddSource("AssemblyInformation.cs", SourceText.From(builder.ToString(), Encoding.UTF8));
}

public void Initialize(GeneratorInitializationContext context)
{

}
}
TestSourceGenerator\Properties\launchSettings.json

Код: Выделить всё

{
"profiles": {
"Profile 1": {
"commandName": "DebugRoslynComponent",
"targetProject": "..\\ConsoleApp1\\ConsoleApp1.csproj"
}
}
}
ConsoleApp1\ConsoleApp1.csproj

Код: Выделить всё



Exe
net7.0
enable
enable







ConsoleApp1\Program.cs

Код: Выделить всё

Console.WriteLine("Name: " + AssemblyInformation.Name);
Console.WriteLine("Name: "  + AssemblyInformation.HumanizedName);
Когда я отлаживаю SourceGenerator с использованием профиля 1, все работает так, как ожидалось..
Но если я пытаюсь скомпилировать ConsoleApp1, он жалуется, что не может. не могу найти Гуманизатор, даже когда он там

Код: Выделить всё

Generator 'SourceGenerator' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was of type 'FileNotFoundException' with message 'Could not load file or assembly 'Humanizer, Version=2.14.0.0, Culture=neutral, PublicKeyToken=979442b78dfc278e' or one of its dependencies. The system cannot find the file specified.'
Что мне не хватает?
Я проверил, что Humanizer является частью файла nuget, когда я упаковываю SourceGenerator.
Копия кода можно найти здесь: https://github.com/AnderssonPeter/TestSourceGenerator

Подробнее здесь: https://stackoverflow.com/questions/746 ... e-solution

Вернуться в «C#»