dotnet / Scaffolding

Code generators to speed up development.
MIT License
633 stars 226 forks source link

Could not get the reflection type for DbContext when using DI #2604

Open DEAN-Cherry opened 8 months ago

DEAN-Cherry commented 8 months ago

I am using DI in a function called AddMyServices

    public static IServiceCollection AddMyServices(this IServiceCollection services)
    {
        services.AddScoped<ITestService, TestService>();
        return services;

    }

So that I can register all my Services in one function with builder.Services.AddMyServices(); in Program.cs However, in this case, I cannot scaffold an api controller and get the following:

Could not get the reflection type for DbContext : Xxx.Data.XxxContext at Microsoft.VisualStudio.Web.CodeGeneration.ActionInvoker.b__6_0() at Microsoft.Extensions.CommandLineUtils.CommandLineApplication.Execute(String[] args) at Microsoft.VisualStudio.Web.CodeGeneration.ActionInvoker.Execute(String[] args) at Microsoft.VisualStudio.Web.CodeGeneration.CodeGenCommand.Execute(String[] args)

If I use builder.Services.AddScoped<ITestService, TestService>(); in Program.cs instead of the function, everything just works fine. And that's pretty weird.

I tried to:

But the problem is still there.


Support Content

version

Entity Framework Core .NET Command-line Tools: 8.0.0 Target framework: .NET 8.0 Operating system: Win 11 23h2 IDE: Visual Studio 2022 17.8.3(latest)

code

Full def of ITestService & TestService

public interface ITestService
{
   public void Test(); 
}
public class TestService: ITestService
{
    public void Test()
    {
       Console.WriteLine("Test");
    }
}
dylanbeattie commented 8 months ago

I'm seeing the same - or very similar - behaviour; looks like calling extension methods from Main() means the aspnet-codegenerator tool can't construct the Program class to extract the DbContext settings.

https://github.com/dotnet/Scaffolding/issues/2623