C# 温莎城堡的生活方式不受尊重
我正在开发一个三层MVC应用程序。数据层包含EF4代码优先DbContext:C# 温莎城堡的生活方式不受尊重,c#,asp.net,asp.net-mvc,castle-windsor,C#,Asp.net,Asp.net Mvc,Castle Windsor,我正在开发一个三层MVC应用程序。数据层包含EF4代码优先DbContext: public class MyDataContext : DbContext { // DbSet<>s... } 和存储库模式: public interface IRepository<T> { T Create(); void Insert(T entity); void Delete(T entity); ... void Save()
public class MyDataContext : DbContext
{
// DbSet<>s...
}
和存储库模式:
public interface IRepository<T>
{
T Create();
void Insert(T entity);
void Delete(T entity);
...
void Save();
}
public class Repository<TEntity> : IRepository<TEntity>
where TEntity: class, new()
{
public Repository(IContextFactory factory)
{
this.context = factory.GetContext();
this.set = factory.Set<TEntity>();
}
...
}
我不知道有什么不对劲——我的测试没有涵盖数据上下文——但在调试模式下,每个web请求都会调用我的数据上下文的构造函数近十几次
编辑:虽然它没有解释为什么
存储库
和MyDataContext
没有被限定到web请求的范围,但我在构造函数中的断点显示了一个相同的调用堆栈,它的构造大约有十几次:MembershipProvider.GetUser->new Repository(IContextFactory)
。我没有显式调用GetUser
-到底是什么原因导致FormsAuthentication调用GetUser这么多次?在Global.asax.cs文件中添加类似的内容:
protected void Application_BeginRequest(object sender, EventArgs args)
{
System.Diagnostics.Debug.WriteLine(this.Request.RequestType + " " + this.Request.RawUrl);
}
连接调试器并验证每个“请求”实际上只有一个请求。也许您有并行运行的ajax请求。或者你可以让你的内容元素(js文件、图像)受到保护,它们的GET正在执行C代码。这是个不错的主意。刷新我今晚正在处理的页面时,跟踪到输出窗口的四行代码:
GET/
,GET/favicon.ico
,GET/control panel/index
,GET/favicon.ico
。仍然是一个谜,为什么数据库会被多次访问(我很确定成员资格是惰性地完成的,表单验证数据被打包到auth cookie中)。即使我明白了这一点,我也遇到了每个IOC的问题。请解决创建新数据连接的问题。
container.Register(
Component.For<MyDataContext>()
.DependsOn(new Hashtable() { {"connectionStringName", "DefaultConnection"} })
.LifestylePerWebRequest());
container.Register(
Component.For<IContextFactory>()
.ImplementedBy<ContextFactory>()
.LifestylePerWebRequest());
container.Register(
Component.For(typeof(IRepository<>))
.ImplementedBy(typeof(Repository<>))
.LifestylePerWebRequest());
protected void Application_BeginRequest(object sender, EventArgs args)
{
System.Diagnostics.Debug.WriteLine(this.Request.RequestType + " " + this.Request.RawUrl);
}