将依赖注入与内存数据库相结合的问题

问题描述 投票:0回答:1

我很好奇为什么当我尝试在程序中使用 DI 时收到此错误,当我在没有 DI 的情况下构建所有内容时,程序工作正常,但当我尝试添加它时,我收到一条错误消息。

enter image description here

enter image description here

https://github.com/przemyslaw12345/DI_LINQ_Nauka.git

Program.cs

var services = new ServiceCollection();
services.AddSingleton<IApp, App>();
services.AddSingleton <IRepository<Employee>, SQLRepository<Employee>>();
services.AddDbContext<SilaGenerycznosciDbContext>();

var serviceProvider = services.BuildServiceProvider();
var app = serviceProvider.GetService<IApp>()!;
app.Run();

SilaGenerycznosciDbContext.cs

    internal class SilaGenerycznosciDbContext : DbContext
{
    public DbSet<Employee> Employees => Set<Employee>();
    public DbSet<BusinessPartner> BusinessPartners => Set<BusinessPartner>();
    public SilaGenerycznosciDbContext(DbContextOptions<SilaGenerycznosciDbContext> option) : base(option)
    {
        
    }
    protected override void OnConfiguring(DbContextOptionsBuilder optionsbuilder)
    {
        base.OnConfiguring(optionsbuilder);
        optionsbuilder.UseInMemoryDatabase("StorageApp"); // making a database with efc as we are using in memory storage need to implement it with this code
    }
}

我在这个网站上搜索了答案(找到了一些似乎是我正在寻找的答案,但它不起作用)并尝试使用 C# 在线库对其进行逻辑处理,但无济于事。

c# .net dependency-injection entity-framework-core
1个回答
0
投票

您的

SQLRepository<TEntity>
Github链接)在构造函数中使用了错误的参数

public SQLRepository(DbContext dbContext,
            Action<TEntity>? itemAddedCallback = null
            /*ItemAdded<TEntity>? itemAddedCallback=null*/)

它应该是

SilaGenerycznosciDbContext
而不是
DbContext
,因为您使用此行仅注册 DbContext 的实现

services.AddDbContext<SilaGenerycznosciDbContext>();

您的代码还存在其他问题 -

services.AddDbContext
应该使用带有选项构造的重载 - 目前它将尝试使用无参数构造函数并失败 - 您的数据库上下文中没有这样的问题。

例如,您可以将数据库上下文注册更改为

builder.Services.AddDbContext<SilaGenerycznosciDbContext>(options => options.UseInMemoryDatabase("StorageApp"));

然后从

OnConfiguring
中删除
SilaGenerycznosciDbContext.cs
方法。这样做的优点是您可以在不同的应用程序中以不同的方式注册数据库上下文。一个 DI 容器将使用
.UseSqlServer
,另一个 -
.UseInMemoryDatabase()

另一种情况,

Action<TEntity>? itemAddedCallback = null
用DI容器解析时永远不会被传递,因为你没有在这一行指定参数

services.AddSingleton<IRepository<Employee>, SQLRepository<Employee>>();

这些可能只是阻止代码正常运行的众多因素中的一小部分。

© www.soinside.com 2019 - 2024. All rights reserved.