我一直在与多个非Web应用程序一起工作Entity Framework
,但一直很难为我找到一种Generic Repository
使用DbContext实施的正确方法。
我搜索了很多东西,许多文章都是关于具有短暂生存期的Web应用程序的。在桌面方法中,我找不到合适的方法。
一种方法是,DbContext per ViewModel
但我不同意将View与Repository层耦合在一起。
另一个以using
这种方式使用子句:
using(var context = new AppDbContext())
{
// ...
}
但是这样我们就不会Unit of Work
也不会使用IoC Containers
。
那么在桌面应用程序中使用DbContext的最佳实践是什么?
ADbContext
是短暂的:它本身代表一个工作单元。如果需要长期的对象状态管理,则可以ObjectStateManager
直接在Entity Framework中使用。
为了确保对a的访问DbContext
,请添加一个接口IDbContextFactory<TDbContext>
(或者仅IMyDbContextFactory
在您只有一个DbContext
类型的情况下),然后将其注入到ViewModels中,并使用其中的一个短命方法DbContext
:
interface IDbContextFactory<TDbContext>
where TDbContext : DbContext
{
TDbContext Create();
}
// Configure:
void ConfigureServices( YourContainer container )
{
container.RegisterSingleton( IDbContextFactory<YourDbContextType1>, // etc );
container.RegisterSingleton( IDbContextFactory<YourDbContextType2>, // etc );
container.RegisterSingleton( IDbContextFactory<YourDbContextType3>, // etc );
}
// Usage:
public class LongLivedViewModel
{
private readonly IDbContextFactory<YourDbContextType3> dbFactory;
public LongLivedViewModel( IDbContextFactory<YourDbContextType3> dbFactory)
{
this.dbFactory = dbFactory ?? throw new ArgumentNullException(nameof(dbFactory));
this.DoSomethingCommand = new RelayCommand( this.DoSomethingAsync )
}
public RelayCommand DoSomethingCommand { get; }
public async RelayCommand DoSomethingAsync()
{
using( YourDbContextType3 db = this.dbFactory.Create() )
{
// do stuff
await db.SaveChangesAsync();
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句