Ninject 和实体框架
我将 Ninject 与 MVC 应用程序一起使用,还使用 EF4.1 Code First。我在尝试测试是否可以从两个不同的浏览器实例发出请求时遇到问题。
基本上,如果我几乎同时在两个浏览器上登录,我会收到一条错误消息,告诉我“创建模型时无法使用上下文”。
现在,我的第一个假设是我有冲突的实例,因此没有正确设置上下文的范围。
我有一个基类上下文,其中包含必要的表,我从中继承。然后,我有一个被注入的工厂,并负责在我请求存储库时实际创建上下文。
public class ContextFactory
{
TContext Create<TContext>( )
}
我需要这样做,因为我的连接字符串是在运行时决定的,所以我不能只使用 web.config 中包含的连接字符串
public class Repository : BaseRepository<MyObject>
{
public Repository(IContextFactory factory) : base(factory)
{
}
}
这个想法是,当我需要我的存储库时,我注入存储库,它有它的自己的注入,创建它的上下文,我可以提供一些默认实现。
我的下一个担忧是我没有正确关闭或销毁某些实例。我使用了其他人的示例来在会话范围内设置某些对象数据,但大多数我尝试使用 OnRequestScope。
I'm using Ninject with an MVC app, also using EF4.1 Code First. I'm getting a problem when trying to test that I can make a request from two different browser instances.
Basically, if I hit login on both browsers at roughly the same time I get an error telling me that "The context cannot be used while the model is being created."
Now, my first assumption is that I have conflicting instances and am therefore not correctly setting the scope on the contexts.
I have a base class context that contains necessary tables, I inherit from this. I then have a factory that is injected, and is responsible for actually creating the context when I request my repository.
public class ContextFactory
{
TContext Create<TContext>( )
}
I need to do this as my connection string is decided at run-time, so I I can't just use the connection string contained in the web.config
public class Repository : BaseRepository<MyObject>
{
public Repository(IContextFactory factory) : base(factory)
{
}
}
The idea being that when I need my repository, I inject the repository, it's has it's own injection, creates its context and I can provide some default implementation.
My next concern is that I'm not correctly closing or destroying some instances. I have used someone elses example for setting certain object data in session scope, but most I try and use OnRequestScope.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
听起来您的
ContextFactory
需要绑定InRequestScope
:您收到的错误似乎表明两个请求 - 来自每个浏览器实例的一个 - 正在尝试使用相同的确切内容你的 EF Context 的实例,这当然是行不通的。
It sounds like your
ContextFactory
needs to be boundInRequestScope
:The error you are receiving seems to indicate that both requests - one from each browser instance - are trying to use the same exact instance of your EF Context, which of course will not work.