【发布时间】:2021-07-12 10:19:05
【问题描述】:
我正在开发一个 API 来使用实体框架从数据库中获取数据。我有一个类库来处理我的通用任务,包括 Repository、UnitOfWork 等。我的 UnitOfWork 类如下。
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using AppPermission.Data.DataContext;
using AppPermission.Data.Models;
using AppPermission.Data.Repositories;
namespace AppPermission.Common.UnitOfWork
{
public class UnitOfWork : IUnitOfWork
{
private readonly DbContext dbContext;
public UnitOfWork(DbContext context)
{
dbContext = context;
}
public int SaveChanges()
{
return dbContext.SaveChanges();
}
public async Task<bool> SaveChangesAsync()
{
return await dbContext.SaveChangesAsync() > 0;
}
public void Dispose()
{
dbContext.Dispose();
GC.SuppressFinalize(this);
}
}
}
我的 API 的 ConfigureServices 如下
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<AppDbContext>();
services.AddSession();
services.AddControllersWithViews();
services.AddRazorPages();
services.AddScoped<IUnitOfWork, UnitOfWork>();
}
我想将API启动中注册的AppDbContext传递给类库中的UnitOfWork。 StackOverflow 中有几个使用(services.BuildServiceProvider) 的解决方案,但是在第一次 API 调用 (GetAll) 之后连接就被处理掉了。有什么办法吗?如果我将我的 UnitOfWork 放在 API 项目本身并更改 UnitOfWork 中的构造函数以接受 AppDbContext,它可以正常工作吗?
【问题讨论】:
-
为什么你的
UnitOfWork对象实现IDisposable?您永远不应该处置由您的 DI 管道生成的对象。管道会为您处理这些问题。从UnitOfWork中删除IDisposable的实现并删除void Dispose()...代码,一切都会正常工作。 -
嗨,安迪,感谢您的 cmets。这是 Microsoft docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions/… 在本文档中推荐的内容。我在这里错过了什么吗?你知道如何将 dbcontext 传递给类库吗?
-
链接的文档很旧(从 2013 年开始),已经过时并且那里的 UOW 实现不使用 DI,但在构造函数中分配
DbContext,这就是为什么它需要IDisposable到Dispose它。您的实现有所不同,因此请参阅@Andy 的评论。为了使 DI 将DbContext注入到您的类中,您无需做任何特别的事情,无论它是否在类库中。 -
顺便说一句,现在在 EF Core 上实现 Generic Repository 和 UOW 被认为是“反模式”,因为 EF Core 已经分别使用
DbSet<T>和DbContext实现了它们。 -
谢谢你,伊万。到时候我会试试的。您是否有任何文件可以让我现在进行推荐的做法?
标签: class asp.net-core dependency-injection dbcontext ef-core-3.1