class - 将 DbContext 传递给类库
问题描述
我正在开发一个 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,它可以正常工作吗?
解决方案
使用 Generic 是个好主意UnitOfWork
:
public class UnitOfWork<TContext> : IUnitOfWork where TContext : DbContext
类构造函数:
public UnitOfWork(TContext context, ILogger<UnitOfWork<TContext>> logger){}
然后像这样将它添加到 IServiceCollection 中:
services.AddScoped<IUnitOfWork, UnitOfWork<MonitoringDbContext>>();
推荐阅读
- python-3.x - 冷启动推荐系统实现
- c - 程序在我打印出值时有效,但在我不打印时无效
- drop-down-menu - 自动完成下拉多选 swiftui
- html - CSS - 如何使带有图标和文本响应的水平手风琴
- google-apis-explorer - Google People API listDirectoryPeople 未返回目录中任何用户的姓名
- javascript - 使用 webpack/react 导入问题
- kubernetes - Kubernetes:如何在 pod nodeAffinity 中使用 Gt 运算符
- python - 在Python中循环检查字符串中的字母
- origen-sdk - 在 Flow.create {} 中调用接口
- python - Dockerfile python无法打开文件