views:

42

answers:

1

I have a profile object in session with profile information for the currently logged in user. I wand to be able to inject it into my business classes so I can do validation etc in them without having to pass it in the parameter list in every method.

I have tried something like this in my ninject module:

Profile profile = HttpContext.Current.Session["Profile"] as Profile;
Bind<Profile>().ToConstant(profile).InTransientScope();

However it blows up with null reference when I do Kernel.Get() in my aspx. The BusinessObject takes a profile via the constructor. If I hard code the profile instead of using the HttpContext then everything seems to work. Not sure if ToConstant is the way to go, I am really looking for something that will get evaluated every time a new BusinessObject is created.

UPDATE

It seems that asking for injection to happen on a page level object inline is too soon for the session collection to be available. If I move in the Kernel.Get call to Page_Load it works just fine.

+4  A: 

I think what's happening to your code is, at the time you're creating the binding, the Session profile is null.

You probably need to do something like this:

Bind<Profile>()
    .ToMethod(context => 
        HttpContext.Current.Session["Profile"] as Profile);
Brian Chavez
HttpContext.Current.Session seems to be null at the time .ToMethod runs.
e36M3
Try setting a breakpoint on your BusinessObject constructor. Use the immediate window to evaluate HttpContext.Current.Session["Profile"] and see if your profile object is there. Also, ensure its type is Profile. If it's not there, then you might have some kind of other problem.
Brian Chavez
The problem is that HttpContext.Current.Session is null, meaning the entire collection is null. I can easily get to HttpContext.Current.User, and that gives the the identity. It's almost like the injection happens before the Session collection is somehow exposed.
e36M3
You might need to examine when you're injecting your objects to make sure they coencide with the correct stage in the ASP.NET page life cycle. http://codebetter.com/blogs//images/codebetter_com/raymond.lewallen/89/o_aspNet_Page_LifeCycle.jpg
Brian Chavez
I don't see any event that has the word Session in it, but you are correct it had to do with that. I moved this injection request into Page_Load that that solved the issue. Clearly Session is not available when you request injection at a page level declaration.
e36M3