Monday, February 4, 2013

Using Ninject to inject session variables into controller properties

According to our JAVA developer, JAVA spring can inject session variables into controller properties. So - I was triggered to see if I could hack something together that resembles this behavior in C#, using Ninject. So here's a quick thing that I put together:
    internal class StandardKernelWithSessionResolution : StandardKernel
    {
        public override IEnumerable Resolve(Ninject.Activation.IRequest request)
        {
            if (request.Target != null && HttpContext.Current != null && HttpContext.Current.Session != null && HttpContext.Current.Session[request.Target.Name] != null)
            {
                Log.Debug("Property {0} is being injected from session", request.Target.Name);
                return new List() { HttpContext.Current.Session[request.Target.Name] };
            }
            return base.Resolve(request);
        }
    }
In your MVC application, you will need to use StandardKernelWithSessionResolution() as opposed to the StandardKernel() call. Also, you will need to instantiate the session variable once, but after that you're good:
    public class HomeController : Controller
    {
        [Inject]
        public Person SessionInjectedPerson { get; set; }

        public ActionResult Index()
        {
            this.SessionInjectedPerson = new Person();
            return View(this.SessionInjectedPerson);
        }

        public ActionResult UpdatePerson()
        {
            this.SessionInjectedPerson.Name = this.SessionInjectedPerson.Name + " > ";
            return this.View("Index",this.SessionInjectedPerson);
        }
It's not very well tested and you it works on the fact that the session entry name is the same as the property, however - it might save you some time.

1 comment:

  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a .Net developer learn from Dot Net Training in Chennai. or learn thru Dot Net Training in Chennai. Nowadays Dot Net has tons of job opportunities on various vertical industry.
    or Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry.

    ReplyDelete