c# - 具有嵌套依赖项的类型的依赖项注入(inject)

标签 c# asp.net-core dependency-injection

我想创建一个包含另一个依赖项的类型。

原因是我可以让 Controller 依赖于具有更抽象功能的基础设施包装器,然后实际访问数据层。

所以这是具有 dbcontext 依赖项的包装器

public Repository(IdbContext context)
{
    _context = context;
}

Controller 构造函数:

private readonly Repository _repo;

public TheController(IRepository repo)
{
    _repo = repo;
}

Startup.cs中,ConfigureServices :

services.AddDbContext<dbContext>(options =>         
    options.UseSqlServer(Configuration.GetConnectionString("dbContext")));
services.AddTransient<IRepository, Repository>();

Program.cs中,

using (var scope = host.Services.CreateScope())
{
    var services = scope.ServiceProvider;
    var context = services.GetRequiredService<dbContext>();
    var _repo = services.GetRequiredService<IRepository>();
    ...
}

GetRequiredService<IRepository>()失败并出现以下异常:

System.InvalidOperationException: 'Unable to resolve service for type 'namespace.Models.IdbContext' while attempting to activate 'namespace.Repositories.Repository'.'

最佳答案

IdbContext 接口(interface)与 dbContext 实现相关联。

假设

public class dbContext: DbContext, IdbContext  {
    //...
}

它失败是因为它未注册,并且提供程序不知道将 IdbContext 注入(inject)存储库时要初始化什么。

services.AddDbContext<IdbContext, dbContext>(options =>         
    options.UseSqlServer(Configuration.GetConnectionString("dbContext")));
services.AddTransient<IRepository, Repository>();

关于c# - 具有嵌套依赖项的类型的依赖项注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51548578/

相关文章:

c# - 什么是依赖注入(inject),我为什么要使用它?

c# - Azure 应用服务 - 更新 .NET Core 运行时

c# - for循环中的迭代变量什么时候递增

c# - asp.net core 中的队列任务

c# - 以 XmlDocument 作为返回类型的 Web 方法在 asp.net core 的 SoapCore 中失败

asp.net-mvc - ASP.NET MVC 中的 DI 与 View 模型

c# - web.config 文件中的自定义配置部分破坏了我的单元测试

c# - 如何使用 C# 代码检测 XSLT 转换中的 "parsing time"?

c# - EF Core 8 无法创建 'DbContext' 类型的 ''

Spring 启动: configuration inheritance