我想创建一个包含另一个依赖项的类型。
原因是我可以让 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/