首页 > 解决方案 > 如何装饰 EF Core 的 DbContext

问题描述

我正在尝试使用 Scrutor 库来装饰 DbContext,以便可以将一些代码注入SaveChanges().

我的装饰器看起来像这样:

public class DbContextDecorator : DbContext
{
  private readonly DbContext _context;

  public DbContextDecorator(DbContext context)
  {
    _context = context
  }

  public override int SaveChanges()
  {
    _context.SaveChanges();
    // some other code
  }
}

我正在使用它

builder.Services.Decorate(typeof(MyContext), typeof(DbContextDecorator));

但是,当我想MyContext在构造函数或使用中检索我的装饰时GetService<MyContext>(),它会永远挂起,看起来像是死锁或什么。

我也尝试将我的装饰器类更改为

public class DbContextDecorator<TContext> : DbContext where TContext : DbContext
{
  private readonly TContext _context;

  public DbContextDecorator(TContext context)
  {
    _context = context
  }
}

把它装饰得像

builder.Services.Decorate(typeof(MyContext), typeof(DbContextDecorator<MyContext>));

但它是一样的,这只是我认为可能有效的错误希望。

我做错了什么还是不能以这种方式装饰 DbContext 并且我需要为它创建接口?

标签: c#entity-frameworkentity-framework-coredecorator

解决方案


推荐阅读