Castle Windsor PerWebRequest Lifestyle is not being honored

五迷三道 提交于 2019-12-11 13:06:52

问题


I'm working on a 3-tier MVC application. The data layer contains an EF4 code-first DbContext:

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

There's also an interface and an implementation for 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;
    }
}

And a repository pattern:

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

The upper tiers access the entities by having IRepository<> injected with castle windsor. Custom providers/modules explicitly .Resolve<>() them as needed.

The data layer is being registered in a castle 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());

I wouldn't know anything was wrong - my tests don't cover the data context - but in debug mode my data context's constructor is getting called nearly a dozen times per web request.

edit: Whilst it does not explain why Repository and MyDataContext aren't getting scoped to web requests, my break point inside the constructor reveals an identical call stack all dozen-or-so times that its constructed: MembershipProvider.GetUser -> new Repository(IContextFactory). I have no explicit calls to GetUser - what in the world would cause FormsAuthentication to call GetUser so many times?


回答1:


Add something like this in your Global.asax.cs file:

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

Hook up with debugger and verify that there realy is just one request per "request". Maybe you have ajax requests running parallelly. Or mayby you have your content elements (js files, images) protected and their gets are executing C# code.



来源:https://stackoverflow.com/questions/11643594/castle-windsor-perwebrequest-lifestyle-is-not-being-honored

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!