我有一个简单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'可能是一个不允许的接口 –