【问题标题】:Windsor Castle IoC - Http Session温莎城堡 IoC - Http 会话
【发布时间】:2011-03-17 01:46:20
【问题描述】:

我正在使用 MVC 3,我有一系列控制器取决于各种存储库,我的存储库中的 1 个依赖于 http 上下文会话。 为了使用 Windsor-Castle IoC,我为每个存储库创建了接口。

如何将当前会话对象向下传递到需要它的存储库?

我曾经能够做到这一点,“解决”会小心地将会话传递到需要它的存储库,不知何故我无法在最新版本(2011 年 2 月 2.5.3 日)中做到这一点:

Protected Overrides Function GetControllerInstance(ByVal requestContext As System.Web.Routing.RequestContext, _
                                                   ByVal controllerType As System.Type) As System.Web.Mvc.IController
    Dim match As IController
    ' 1 or more components may need the session,
    ' adding it as a (possible) dependency
    Dim deps As New Hashtable
    deps.Add("session", HttpContext.Current.Session)
    match = container.Resolve(controllerType, deps)
    Return match
End Function

谢谢,文森特

【问题讨论】:

    标签: castle-windsor ioc-container


    【解决方案1】:

    仔细查看您的设计。当您查看它的功能时,您的存储库根本不依赖于会话,而是依赖于您存储在会话中的一些数据。对要从会话中提取的内容创建一个抽象,并让存储库依赖于这种抽象。例如:

    public interface IUserProvider
    {
        int GetCurrentUserId();
    }
    
    public class SomeRepository : ISomeRepository
    {
        private readonly IUserProvider userProvider;
    
        public SomeRepository(IUserProvider userProvider)
        {
            this.userProvider = userProvider;
        }
    }
    

    现在您可以创建该抽象的以下实现:

    private class HttpSessionUserProvider : IUserProvider
    {
        public int GetCurrentUserId()
        {
            return (int)HttpContext.Current.Session["UserId"];
        }
    }
    

    您可以在 IoC 配置中注册此具体类型。

    这样会好很多,因为您不想让您的存储库直接依赖于 HTTP 会话。这使测试变得更加困难,并在您的存储库和特定的表示技术之间建立了依赖关系。

    【讨论】:

      【解决方案2】:

      控制器工厂的唯一职责是创建控制器。不处理会话或任何其他依赖项。最好将会话注册为单独的组件并让 Windsor 自动装配它。从那里删除“deps”哈希表并注册:

        container.Register(Component.For<HttpSessionStateBase>()
            .LifeStyle.PerWebRequest
            .UsingFactoryMethod(() => new HttpSessionStateWrapper(HttpContext.Current.Session)));
      

      然后在你的控制器中注入HttpSessionStateBase

      顺便说一句:控制器已经可以访问会话,如果您只是将会话注入控制器,则无需这样做。

      【讨论】:

      • container.Register(Component.For&lt;HttpSessionStateBase&gt;() .UsingFactoryMethod(() =&gt; new HttpSessionStateWrapper(HttpContext.Current.Session)) .LifestylePerWebRequest()); 获取更新的代码
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多