我仍然会收到这样的错误:
类型' System.InvalidOperationException'的例外情况发生在EntityFramework.dll中,但未在用户代码中处理 附加信息:由于DbContext已被丢弃,因此无法完成操作。
我正在使用Ninject,当我使用注入的存储库(InRequestScope
)到HomeController
时,一切正常,但是当我使用注入的类InSingletonScope
时,它注入了另一个存储库通过InRequestScope
,我得到了这个错误。
我的InSingletonScope
课程:
public class SettingsManager : ISettingsManager
{
private readonly IConfigurationRepository _configurationRepository;
private readonly Lazy<ApplicationSettings> _applicationSettings;
public ApplicationSettings Application { get { return _applicationSettings.Value; } }
private SettingsManager(IConfigurationRepositorycontext)
{
_configurationService = context;
_applicationSettings = new Lazy<ApplicationSettings>(() => new ApplicationSettings(context));
}
}
ApplicationSettings
上课:
public class ApplicationSettings : ApplicationSettingsBase
{
private readonly IConfigurationRepository _configurationRepository;
public ApplicationSettings(IConfigurationRepository context)
{
_configurationRepository= context;
}
public string GetItem()
{
return _configurationService.GetApplicationConfiguration(4).First().Value.ToString();
}
}
我的ConfigurationRepository
:
public class ConfigurationRepository : BaseRepository<Configuration>, IConfigurationRepository
{
public ConfigurationRepository(DbContext _dbContext)
: base(_dbContext)
{
}
public IQueryable<ConfigurationDTO> GetApplicationConfiguration(int domainId)
{
return _dbContext.Set<Configuration>()
.Where(x => x.DomainId == 5)
.Select(x => new ConfigurationDTO
{
Name = x.Name,
Value = x.Value
});
}
}
在此存储库中,我收到错误消息。
我的NinjectWebCommon.RegisterServices
方法:
kernel.Bind<ISettingsManager>().To<SettingsManager>().InSingletonScope();
kernel.Bind<IConfigurationRepository>().To<ConfigurationRepository>().InRequestScope();
kernel.Bind<DbContext>().To<EntitiesDbContext>().InRequestScope();
哪里可能是问题?
EDIT 当我将DbContext更改为EntitiesDbContext:
时,问题就消失了 public class ConfigurationRepository : BaseRepository<Configuration>, IConfigurationRepository
{
public ConfigurationRepository(EntitiesDbContext _dbContext)
: base(_dbContext)
{
}
}
所以我在Ninject中的绑定是错误的吗?
kernel.Bind<DbContext>().To<EntitiesDbContext>().InRequestScope();
为什么?
我有新模特:
public partial class EntitiesDbContext : DbContext
{
public EntitiesDbContext ()
: base("name=EntitiesDbContext ")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<Configuration> Configuration { get; set; }
}
}