问题描述
我正在尝试在 DbContext
中做类似的事情:
I'm trying to do something like in my DbContext
:
public System.Action<IEnumerable<EntityEntry>> OnSave;
public override int SaveChanges() {
if(OnSave != null)
OnSave(ChangeTracker.Entries());
return base.SaveChanges();
}
然后DI(AutoFac) DbContext
进入另一个可以连接到'OnSave'函数的类。
Then DI (AutoFac) the DbContext
into another class which can hook into the 'OnSave' function.
这种情况发生时,我正在寻找一个真实的来源。
I'm looking for a single source of truth when this happens.
我认为将 DbContext
注入多个位置时,这不会起作用或不可靠,因为我敢肯定我们结束了对于每个被注入到的地方,都有多个 DbContext
实例。
I don't think this will work or be reliable when DbContext
is injected into multiple places since I'm pretty sure we end up with multiple instances of DbContext
for every place it's injected into.
推荐答案
听起来像您希望您的 OnSave
方法成为单例(在您的 DbContext
的所有实例中使用的方法相同)
Sounds like you want your OnSave
method to be a singleton (the same method used in all instances of your DbContext
).
解决此问题的一种方法是将 Action
移至新类:
One way to solve this is to move your Action
to a new class:
public class MySaveEventHandler {
public System.Action<IEnumerable<EntityEntry>> OnSave;
}
然后将其作为单例添加到Startup.cs中以使其可用于依赖项注入:
Then add it as a singleton in your Startup.cs to make it available for dependency injection:
services.AddSingleton<MySaveEventHandler>();
然后更改 DbContext
构造函数以接受通过DI并在您的 SaveChanges
方法中使用它:
Then change you DbContext
constructor to accept that via DI and use that in your SaveChanges
method:
MySaveEventHandler _mySaveEventHandler;
public MyDbContext(DbContextOptions<MyDbContext> options, MySaveEventHandler mySaveEventHandler) : base(options) {
_mySaveEventHandler = mySaveEventHandler;
}
public override int SaveChanges() {
if(_mySaveEventHandler.OnSave != null)
_mySaveEventHandler.OnSave(ChangeTracker.Entries());
return base.SaveChanges();
}
设置 OnSave
方法,您只需通过DI获取单个 MySaveEventHandler
实例并进行设置。然后 DbContext
的每个实例都将使用它。
To set the OnSave
method, you simply get your single MySaveEventHandler
instance via DI and set it. Then every instance of your DbContext
will use it.
侧面说明:您可以使用事件代替委托。确实,我认为这不会带来很大的功能差异,但是这里有一些有趣的文章:
Side note: You could use an event instead of a delegate. Really I don't think it'll make much of a functional difference, but there's some interesting reading about it here: https://docs.microsoft.com/en-us/dotnet/csharp/distinguish-delegates-events
这篇关于回调EFCore中的SaveChanges?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!