gpt4 book ai didi

c# - 使 .NET Core Web 应用程序可以通过接口(interface)而不是直接引用 EF DbContext

转载 作者:行者123 更新时间:2023-11-30 20:31:17 24 4
gpt4 key购买 nike

我有一个场景,在 StartUp.cs 中我需要使用 DbContext 设置 EF,如下所示:

public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddDbContext<TestProjDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

services.AddMvc();
}

但是,我的解决方案分为多个层。例如:Api、数据、域、服务...

我正在努力使 Api 项目仅引用域和服务项目。但是,DbContext 把我搞得一团糟。 TestProjDbContext 与我的存储库、迁移、工作单元类等一起位于数据项目中。

在我的域项目中,我有一堆接口(interface),如 IUnitOfWork、ICustomerRepository 等。我还在这个项目中创建了一个 ITestProjDbContext 接口(interface),我想我可以以某种方式将它传递到 StartUp.cs 中的 services.AddDbContext。然而,这似乎是不可能的。

如何在 Api 不知道数据层而只知道域层的情况下将我的 TestProjDbContext.cs 文件保存在数据层中?或者 DbContext 不应该在数据层中,而只是在不使用接口(interface)的情况下位于域层中吗?

最佳答案

是的,可以为您的 DbContext 提供一个接口(interface),并在您的 startup.cs注入(inject)它,并且在您的 Api Controller 中使用接口(interface)(例如:ITestDbContext)。

这是一个通过代码示例详细说明这一点的演练。我不想复制粘贴和抄袭它,所以我已经根据您的情况用相关代码为您制定了步骤。请务必阅读原始博客文章以全面了解其工作原理。

杰里·佩尔瑟 - Resolve your DbContext as an interface using the ASP.NET 5 dependency injection framework

第 1 步 - 声明您的 ITestDbContext 接口(interface)并添加您的 DbSets

public interface ITestDbContext
{
DbSet<Episode> Episodes { get; set; }
DbSet<ApplicationUser> Users { get; set; }
// ....
int SaveChanges();
Task<int> SaveChangesAsync(CancellationToken cancellationToken);
}

第 2 步 - 将 ITestDbContext 实现为具体类 TestDbContext

public class TestDbContext : IdentityDbContext<ApplicationUser>, ITestDbContext
{
public virtual DbSet<Episode> Episodes { get; set; }

public ApplicationDbContext()
{
// ...
}
}

第 3 步 - 在 ConfigureServices 方法中的接口(interface)上设置依赖注入(inject)。

public void ConfigureServices(IServiceCollection services)
{
...

// Add EF services to the services container.
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<TestDbContext>(options =>
options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));

// Register the service and implementation for the database context
services.AddScoped<ITestDbContext>(provider => provider.GetService<TestDbContext>());

// ...
}

需要注意的关键行如下

services.AddScoped<ITestDbContext>(provider => provider.GetService<TestDbContext>());

注意:请阅读作者 Jerrie Pelserhis blog post 中如何使用此方法。 .

第 4 步 - 在 Api Controller 中使用 ITestDbContext 接口(interface)

public class EpisodesController : Controller
{
private readonly ITestDbContext dbContext;

public EpisodesController(ITestDbContext dbContext)
{
this.dbContext = dbContext;
}

...
}

关于c# - 使 .NET Core Web 应用程序可以通过接口(interface)而不是直接引用 EF DbContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43463508/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com