【问题标题】:Castle Windsor PerWebRequest Lifestyle is not being honoredCastle Windsor PerWebRequest Lifestyle 没有受到尊重
【发布时间】:2012-07-25 06:01:46
【问题描述】:

我正在开发一个 3 层 MVC 应用程序。数据层包含一个 EF4 代码优先的 DbContext:

public class MyDataContext : DbContext
{
    // DbSet<>s...
}

还有 DI 的接口和实现:

public interface IContextFactory
{
    MyDataContext GetContext();
}

public class ContextFactory : IContextFactory
{
    readonly MyDataContext context;
    public ContextFactory(MyDataContext context)
    {
        this.context = context;
    }

    public MyDataContext GetContext()
    {
        return this.context;
    }
}

还有一个存储库模式:

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>();
    }
    ...
}

上层通过将IRepository&lt;&gt; 注入温莎城堡来访问实体。自定义提供程序/模块根据需要明确.Resolve&lt;&gt;()

数据层正在城堡IWindsorInstaller注册:

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());

我不知道有什么问题——我的测试没有涵盖数据上下文——但在调试模式下,我的数据上下文的构造函数在每个网络请求中被调用了近十几次。

编辑:虽然它没有解释为什么 RepositoryMyDataContext 没有被限定为 Web 请求,但我在构造函数中的断点显示了一个完全相同的调用堆栈。所以它的构造:MembershipProvider.GetUser -&gt; new Repository(IContextFactory)。我没有明确调用GetUser - 到底是什么导致 FormsAuthentication 调用 GetUser 这么多次?

【问题讨论】:

    标签: c# asp.net asp.net-mvc castle-windsor


    【解决方案1】:

    在您的 Global.asax.cs 文件中添加类似的内容:

        protected void Application_BeginRequest(object sender, EventArgs args)
        {
            System.Diagnostics.Debug.WriteLine(this.Request.RequestType + " " + this.Request.RawUrl);
        }
    

    连接调试器并验证每个“请求”确实只有一个请求。也许您有并行运行的 ajax 请求。或者,也许您的内容元素(js 文件、图像)受到保护,并且它们正在执行 C# 代码。

    【讨论】:

    • 一个不错的主意。刷新我今晚一直在处理的页面,将四行跟踪到输出窗口:GET /GET /favicon.icoGET /control-panel/indexGET /favicon.ico。为什么数据库被多次访问仍然是一个谜(我很确定成员资格是懒惰地完成的,并且表单身份验证数据被打包到 auth cookie 中)。即使我弄清楚了,我也遇到了每个IOC.Resolve&lt;IRepository&lt;EntityType&gt;&gt; 创建新数据连接的问题。
    猜你喜欢
    • 2012-08-08
    • 1970-01-01
    • 2011-08-12
    • 1970-01-01
    • 2013-12-16
    • 2015-10-03
    • 2012-07-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多