You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Core中依赖注入无法识别仓储(IRepo)的问题求助

Fixing Dependency Injection for IRepo with EF6.2 in .NET Core

Alright, let's break down why your IRepo isn't being recognized by .NET Core's DI system and how to fix it step by step. The core issues here are unregistered services, EF6's non-native support for .NET Core DI, and a potential conflict with your base controller's constructor.

Step 1: Register Your Repository and Its Implementation

.NET Core's DI container doesn't automatically pick up custom interfaces and their concrete implementations—you have to explicitly tell it what to inject. First, confirm you have a concrete class for IRepo (like Repo), then add this registration to your service configuration:

For .NET 6+ (Program.cs):

var builder = WebApplication.CreateBuilder(args);

// Register IRepo with its concrete implementation (scoped is standard for web apps)
builder.Services.AddScoped<IRepo, Repo>();

// Rest of your service setup (controllers, etc.)
builder.Services.AddControllers();

For .NET Core 3.1 or earlier (Startup.cs):

public void ConfigureServices(IServiceCollection services)
{
    services.AddScoped<IRepo, Repo>();
    services.AddControllers();
    // ... other services
}

Step 2: Properly Register EF6's DbContext

EF6 wasn't built for .NET Core's DI system, so you can't use EF Core's AddDbContext method. Instead, manually register your SampleContext by providing a factory that creates it with your connection string:

.NET 6+ Example:

builder.Services.AddScoped<SampleContext>(sp => 
{
    var connectionString = builder.Configuration.GetConnectionString("SampleConnection");
    return new SampleContext(connectionString);
});

.NET Core 3.1 Example:

public void ConfigureServices(IServiceCollection services)
{
    services.AddScoped<SampleContext>(sp => 
    {
        var connectionString = Configuration.GetConnectionString("SampleConnection");
        return new SampleContext(connectionString);
    });
    // ... other services
}

Don't forget to define your connection string in appsettings.json:

{
  "ConnectionStrings": {
    "SampleConnection": "Server=your-server;Database=your-db;Trusted_Connection=True;"
  }
}

Step 3: Fix the Base Controller's Constructor

Your base controller has a parameterless constructor that passes null to the repository. This can cause DI to fall back to this constructor instead of injecting IRepo, leaving _repository as null. Here are two fixes:

If you don't need it for testing or non-DI scenarios, delete it to force DI to use the injectable constructor:

public class BaseController : Controller 
{
    protected IRepo _repository;

    public BaseController(IRepo repository) 
    {
        _repository = repository ?? throw new ArgumentNullException(nameof(repository));
    }
}

Option 2: Prioritize the Injectable Constructor (If You Need the Parameterless One)

If you must keep the parameterless constructor (e.g., for unit testing), use [ActivatorUtilitiesConstructor] to tell DI to prioritize the injectable version:

public class BaseController : Controller 
{
    protected IRepo _repository;

    [ActivatorUtilitiesConstructor]
    public BaseController(IRepo repository) 
    {
        _repository = repository ?? throw new ArgumentNullException(nameof(repository));
    }

    // Only use this for non-DI scenarios (like testing)
    public BaseController() : this(null) { }
}

Step 4: Ensure Your Repository Uses the DbContext

Make sure your concrete Repo class accepts SampleContext via its constructor so DI can inject it:

public class Repo : IRepo 
{
    private readonly SampleContext _context;

    public Repo(SampleContext context) 
    {
        _context = context ?? throw new ArgumentNullException(nameof(context));
    }

    // Implement your repository methods using _context...
}

Final Checks

  • Double-check that all services (IRepo, Repo, SampleContext) are registered in your service configuration.
  • Confirm your controller has no other unregistered dependencies in its constructor.
  • Test your API endpoint to verify the repository is now being injected correctly.

内容的提问来源于stack exchange,提问作者Alex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:22:23