Ninject, how to inject an object living in the session into my business class?
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 wor开发者_高级运维k. 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.
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);
精彩评论