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.

No comments:

Post a Comment