【问题标题】:Pass DbContext to class library将 DbContext 传递给类库
【发布时间】: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,这就是为什么它需要 IDisposableDispose它。您的实现有所不同,因此请参阅@Andy 的评论。为了使 DI 将 DbContext 注入到您的类中,您无需做任何特别的事情,无论它是否在类库中。
  • 顺便说一句,现在在 EF Core 上实现 Generic Repository 和 UOW 被认为是“反模式”,因为 EF Core 已经分别使用 DbSet&lt;T&gt;DbContext 实现了它们。
  • 谢谢你,伊万。到时候我会试试的。您是否有任何文件可以让我现在进行推荐的做法?

标签: class asp.net-core dependency-injection dbcontext ef-core-3.1


【解决方案1】:

使用通用UnitOfWork 是个好主意:

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

类构造函数:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-18
    • 2020-06-05
    • 2019-02-04
    • 1970-01-01
    • 2021-12-02
    • 1970-01-01
    相关资源
    最近更新 更多