c# - 如何装饰 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 并且我需要为它创建接口?
解决方案
推荐阅读
- javascript - 在 JavaScript 中将地图转换为二维数组
- .htaccess - 阻止 htaccess 文件中的完整 IP 范围
- javascript - 自定义 Google 表单 HTML 上传文件按钮
- perl - Perl 打印匹配和来自 file1 的匹配字符串与 file2 匹配的无匹配字符串与百万条记录匹配
- node.js - 使用来自 Docker 的 env 变量的 React 连接被拒绝错误
- mysql - 为列的不同值附加其他记录的值
- django - 将 Django 模型数据保存到派生类的数据库中
- python-3.x - Pandas 应用函数 - args 它是如何传递的
- bash - 如果第一个第二和第三个字段相同,我如何使用排序或其他 bash cmd 从所有行中获取 1 行
- php - 在 Laravel 中使用 storeAs 重命名图像和上传失败