我正在使用具有上下文和ninject作为IOC的存储库模式。我有一个服务来处理在数据库中获取和设置页面属性。
public class MyContext : DbContext
{
public MyContext() : base ("DefaultConnection")
{
}
public DbSet<PageProperty> PageProperties { get; set; }
public DbSet<Contact> Contacts { get; set; }
}
public class DefaultRepository : IRepository
{
MyContext _context;
public DefaultRepository(MyContext context)
{
_context = context;
}
public IQueryable<PageProperty> PageProperties { get { return _context.PageProperties; } }
public IQueryable<Contact> Contacts { get { return _context.Contacts; } }
}
public class ModuleLoader : NinjectModule
{
public ModuleLoader()
{
}
public override void Load()
{
var context = new MyContext();
context.Database.Initialize(false);
Bind<MyContext>().ToConstant(context).InSingletonScope();
Bind<IRepository>().To<DefaultRepository>();
Bind<IPagePropertyProvider>().To<DefaultPagePropertyProvider>().InSingletonScope();
}
}
public class DefaultPagePropertyProvider : IPagePropertyProvider
{
IRepository _repository;
object _syncLock = new object();
public DefaultPagePropertyProvider (IRepository repository)
{
_repository = repository;
}
public string GetValue(string pageName, string propertyName
{
lock (_syncLock)
{
var prop = page.PageProperties.FirstOrDefault(x => x.Property.Equals(propertyName) && x.PageName.Equals(pageName)).Value;
return prop;
}
}
public void SetValue(string pageName, string propertyName, string value)
{
var pageProp = _repository.PageProperties.FirstOrDefault(x => x.Property.Equals(propertyName) && x.PageName.Equals(pageName));
pageProp.Value = value;
_repository.SaveSingleEntity(pageProp);
}
}
在我看来,我正在做3个ajax调用,一个用于从联系人中获取列表以填写表,一个用于确定我有多少页面的ajax调用,具体取决于我正在使用的页面大小,以及一个ajax调用设置我想要使用的页面大小。所以一个选择框改变了页面大小(每页有多少个联系人:[30]),一个显示联系人的表(从jquery生成decifers json生成),最后是一个包含要点击的页码列表的div。工作流程是,调用GetContacts()
,此函数会查询PageProperties
以查找要使用的页面大小,然后调用GetPages()
,此函数还会查询PageProperties
以查找要使用的页面大小,SetPageSize()
设置页面大小。因此,当从div中选择页面时,会使用GetContacts()
和GetPages()
,SetPageSize()
然后在选择框更改事件被触发时调用GetContacts()
和GetPages()
。 GetContacts()
和GetPages()
仅在第一个SetPageSize()
$.ajax
请求为done()
并且该函数中有success
时才会被调用。
现在,在我在lock(syncLock)
服务中添加DefaultPageProperty
之前,在我将InSingletonScope
添加到该服务和上下文之前,我遇到了两个错误。
连接未关闭。连接的当前状态是连接。
无法多次将EdmType映射到CLR类
我假设因为连接处于connecting
状态,上下文被重用并重用和重用,所以我认为将它放到SingletonScope()
意味着只建立了一个连接,然后我对DefaultPageProperty
的想法是一样的,然后因为我正在对该服务进行异步调用,我应该锁定数据库查询。
它有效,问题不存在。但是我不知道在我使用的模式中我所做的事情是否正确,我想知道我是否错过了一些基本的东西?我的问题是,这是一个适当/可行的解决方案,不会在以后产生任何警告吗?我实际上是解决了这个问题还是只创造了更多?
答案 0 :(得分:0)
我现在重新设计了我的上下文。
我有我的上下文,然后我实现IDbContextFactory<TContext>
DefaultContextFactory<MyContext>
并注入它们。
在公共构造函数_context = contextFactory.Create();
中的存储库中。
然后在整个存储库中我只使用_context.WhatEver()
并且很好。
我也在ModuleLoader
Bind<IRepository>().To<DefaultRepository>().InTransientScope()
中做过,以便每次调用它都会创建一个新的存储库!
我不需要存储库工厂,因为我只有一个存储库!