首页 > 解决方案 > 将 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,它可以正常工作吗?

标签: classasp.net-coredependency-injectiondbcontextef-core-3.1

解决方案


使用 Generic 是个好主意UnitOfWork

public class UnitOfWork<TContext> : IUnitOfWork where TContext : DbContext

类构造函数:

public UnitOfWork(TContext context, ILogger<UnitOfWork<TContext>> logger){}

然后像这样将它添加到 IServiceCollection 中:

services.AddScoped<IUnitOfWork, UnitOfWork<MonitoringDbContext>>();

推荐阅读