Linq to SQL 和请检查 Castle IoC 容器健全性
我刚刚开始将 Linq to SQL 和 Windsor Castle IoC 容器用于新的 Web 应用程序,尽管在初步测试中一切似乎都正常,但我确实可以对其进行健全性检查。
当我尝试在应用程序的不同部分使用 Linq 从数据库中提取对象,然后在数据库中更新它们时,我遇到了问题。由于它们来自不同的数据上下文,我无法保存更改。
因此,我制作了一个跨应用程序使用的单一数据上下文 - 希望基于每个 Web 请求。 - 这是解决问题的合理方法吗?
它看起来像这样:
public class DataContextAccessor : IDataContextAccessor
{
private readonly DataContext dataContext;
public DataContextAccessor(string connString)
{
dataContext = new DataContext(connString);
}
public DataContext DataContext { get { return dataContext; } }
}
我使用 Castle 来实例化它,如下所示:
<component id="DataContextAccessor" service="DomainModel.Repositories.IDataContextAccessor, DomainModel"
type="DomainModel.Repositories.DataContextAccessor, DomainModel" lifestyle="PerWebRequest">
</component>
然后每当我想在类中访问数据库时,我只需在构造函数中声明 IDataContext datacontext
。
- 这会(如我希望的那样)为每个网络请求创建一个单一的数据上下文 - 并且当许多请求同时进入时不会给我带来任何竞争问题吗?
I've just started using both Linq to SQL and Windsor Castle IoC container for a new web app and, although things seem to be working OK in preliminary tests, I could really do with a sanity check on it.
I was running into problems when I tried to pull objects out of the database using Linq in different parts of the app and then updating them in the database. As they were from different data contexts I couldn't save the changes.
So I have made a single datacontext used across the application - hopefully on a per web request basis. - Is this a reasonable way to fix the problem?
It looks like this:
public class DataContextAccessor : IDataContextAccessor
{
private readonly DataContext dataContext;
public DataContextAccessor(string connString)
{
dataContext = new DataContext(connString);
}
public DataContext DataContext { get { return dataContext; } }
}
I used Castle to instiantiate this like so:
<component id="DataContextAccessor" service="DomainModel.Repositories.IDataContextAccessor, DomainModel"
type="DomainModel.Repositories.DataContextAccessor, DomainModel" lifestyle="PerWebRequest">
</component>
Then whenever I want to get at the database in a class I am just declaring IDataContext datacontext
in my the constructor.
- Will this (as I hope) create a single data context for each web request - and not give me any race problems when many requests are coming in at the same time?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我可以看到您将在这里遇到的问题是,如果您的接口 IDataContextAccessor 公开 DataContext 属性,如下所示:
问题是您实际上已将接口与 linq 创建的 DataContext 紧密耦合,这意味着模拟和单元测试将接近就不可能。
The problem I can see you are going to have here is if your interface IDataContextAccessor exposes the DataContext property like this:
The problem with this is that you have actually tightly coupled your interface to the DataContext created by linq meaning mocking and unit testing will be near on impossible.