在引导HttpContext Scoped后将实例注入StructurMap

时间:2010-04-27 16:05:31

标签: asp.net structuremap

我正在尝试在asp.net MVC应用程序中使用StructureMap,而不是使用HttpSession来存储实例。

我的简单测试课程:

public interface ICurrentSession
{
   User User { get; set; }
}

public class CurrentSession : ICurrentSession
{
   public User User { get; set; }
}

以下是我的引导程序中调用的相关注册表代码:

x.For<ICurrentSession>().HttpContextScoped().Use<CurrentSession>();

然后在我对用户进行身份验证后,我称之为:

var session = new CurrentSession {User = user};
ObjectFactory.Inject<ICurrentSession>(session);

但是每次我调用ObjectFactory.GetInstance()时,它都会为每个会话返回相同的CurrentSession实例(多个用户登录的浏览器)。我做错了什么,或者我如何注入一个CurrentSession并为每个登录的用户/会话确定范围?

1 个答案:

答案 0 :(得分:2)

目前尚不清楚为什么要尝试注入实例(这将覆盖您的注册码)。您应该只检索作用于当前请求的当前实例,然后设置用户。在该请求中对ICurrentSession的任何进一步请求将获得相同的实例。

在对用户进行身份验证后,请致电:

ObjectFactory.GetInstance<ICurrentSession>().User = user;

您问题中的注册码仅将实例范围限定为当前的HTTP请求。如果您希望实例在多个请求中生存,并且为整个ASP.NET会话生存,则需要使用HttpSession生命周期。这个生命周期没有一种方便的方法(我会警告它没有经过严格的测试,因为我们不使用它),但它可用:

x.For<ICurrentSession>()
  .LifecycleIs(Lifecycles.GetLifecycle(InstanceScope.HttpSession)))
  .Use<CurrentSession>();