views:

119

answers:

1

I'm trying to use StructureMap in an asp.net MVC application instead of using HttpSession to store instances.

My simple test class:

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

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

Here is the relevant registry code which is called in my bootstrapper:

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

And then after I authenticate a user, I call this:

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

However everytime I call ObjectFactory.GetInstance() it returns the same CurrentSession instance for each session (multiple browsers with multiple user's logged in). What am I doing wrong, or how can I inject a CurrentSession and have it scoped for each user/session logged in?

+1  A: 

It isn't clear why you are trying to inject an instance (which will override your registration code). You should just retrieve the current instance scoped to the current request and then set the user. Any further requests for ICurrentSession within that request will get the same instance.

After you authenticate a user, call:

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

The registration code in your question will scope the instance to the current HTTP request only. If you want the instance to survive across multiple requests, and live for the entire ASP.NET Session, you need to use the HttpSession lifecycle. There isn't a convenience method for this lifecycle (and I'll warn it isn't heavily tested, as we don't use it), but it is available:

x.For<ICurrentSession>()
  .LifecycleIs(Lifecycles.GetLifecycle(InstanceScope.HttpSession)))
  .Use<CurrentSession>();
Joshua Flanagan
That makes sense. However, I assume that separate Requests within the same Session will receive a different instance of CurrentSession?
mxmissile
Yes, I've updated my answer to make it work across requests.
Joshua Flanagan