I have a Class Library project First.csproj with one file ICar.cs:
namespace First
{
public interface ICar
{
string Name { get; set; }
}
}
I have an empty Class Library project Second.csproj and Analyzer (source generator) project Second.Generator.csproj:
- First.csproj - has no project references
- Second.csproj - has references to First.csproj and Second.Generator.csproj
- Second.Generator.csproj - has no project references
I want to write Second.Generator.csproj MySourceGenerator.cs which takes Second.csproj, search all its Class Library project references (First.csproj in this case) and implement all its interfaces. Result should be this generated code:
namespace Second
{
public class Car : First.ICar
{
public string Name { get; set; }
}
}
Problem is that I cannot access referenced projects in source generator. I have tried to use reflection:
namespace Second.Generator
{
[Generator]
public class MySourceGenerator : ISourceGenerator
{
public void Initialize(GeneratorInitializationContext context)
{
}
public void Execute(GeneratorExecutionContext context)
{
var first = context.Compilation.References.First(); //this is First.dll
var assembly = Assembly.LoadFrom(first.Display);
}
}
}
But I cannot load the assembly:
Could not load file or assembly 'file:///...First\bin\Debug\net6.0\ref\First.dll' or one of its dependencies. Reference assemblies should not be loaded for execution. They can only be loaded in the Reflection-only loader context.
Any help will be appreciated. Thank you.