我有一個簡單DbContext
看起來像:的DbContext和範圍依賴
public class MyDbContext : DbContext
{
private readonly IUserContext _userContext;
public MyDbContext(IUserContext userContext) : base("DefaultConnectionString")
{
_userContext = userContext;
Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyDbContext, Configuration>());
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// ... Here I need to creates some filters using the IUserContext dependency
base.OnModelCreating(modelBuilder);
}
}
這DbContext
使用Func<T>
工廠,using the guidelines in the Simple Injector documentation有線:container.RegisterFuncFactory<DbContext, MyDbContext>(Lifestyle.Scoped);
public static void RegisterFuncFactory<TService, TImpl>(
this Container container, Lifestyle lifestyle = null)
where TService : class
where TImpl : class, TService
{
lifestyle = lifestyle ?? Lifestyle.Transient;
var producer = lifestyle.CreateProducer<TService, TImpl>(container);
container.RegisterSingleton<Func<TService>>(producer.GetInstance);
}
但apperently,這種簡單的情況下是不可能的DbContext
因爲此消息:
目標上下文'MyDbContext'不可構造。添加一個默認的 構造函數或提供IDbContextFactory的實現。
我真的不喜歡的IDbContextFactory
的想法,所以唯一的解決辦法,我能想出是去除依賴於MyDbContext
,將其設置爲一個屬性,修改RegisterFuncFactory
方法和手動初始化的背景:
internal static void RegisterFuncFactory<TService, TImpl>(this Container container, Func<TImpl> instanceProducer, Lifestyle lifestyle = null) where TService : class where TImpl : class, TService
{
lifestyle = lifestyle ?? Lifestyle.Transient;
var producer = lifestyle.CreateProducer<TService>(instanceProducer, container);
container.Register<Func<TService>>(() => producer.GetInstance, Lifestyle.Singleton);
}
container.RegisterFuncFactory<DbContext, MyDbContext>(() => new MyDbContext
{
UserContext = container.GetInstance<IUserContext>()
}, Lifestyle.Scoped);
儘管它不夠優雅,但是還有其他更好的方法來滿足我的需求嗎?我喜歡明確依賴上下文,但似乎不可能。
UPDATE
錯誤是來自:
'System.Data.Entity.Migrations.Infrastructure.MigrationsException' 發生在EntityFramework.dll但在用戶代碼
沒有處理
在此代碼查詢方法這裏的return語句:
internal sealed class EntityFrameworkRepository<TEntity> : IEntityWriter<TEntity>, IEntityReader<TEntity> where TEntity : Entity
{
private readonly Func<DbContext> _contextProvider;
public EntityFrameworkRepository(Func<DbContext> contextProvider)
{
_contextProvider = contextProvider;
}
public IQueryable<TEntity> Query()
{
var context = _contextProvider();
return context.Set<TEntity>().AsNoTracking();
}
// Methods removed for brevity
}
誰給你這個消息:
這是然後在根組成像有線? EF遷移? – Steven
是的,錯誤來自EntityFramework中發生的'System.Data.Entity.Migrations.Infrastructure.MigrationsException'。dll,但沒有在用戶代碼中處理返回statemenet在這裏:var context = _contextProvider();返回context.Set().AsNoTracking();' –
janhartmann
@janhartmann什麼是實體(約束)?我認爲你也應該指定一個'class'約束,因爲現在'TEntity'可能是一個不允許的接口 –