0

I have a class to hold session like this

public class SessionService : ISession
{
    public HttpContext Context { get; set; }

    public SessionService(HttpContext context)
    {
        this.Context = context;
    }
}

I want to be able to inject the session object in various places in my MVC3 app. I have this interface

interface ISession
{
    HttpContext Context { get; set; }
}

I am using ninject to bind the session class to the interface like this

private void RegisterDependencyResolver()
{
    var kernel = new StandardKernel();
    kernel.Bind<ISession>().To<SessionService>();
    DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));
}

My problem is how to pass the Httpcontext parameter into the SessionService constructor.

Any pointers most appreciated.

Thanks

tereško
  • 58,060
  • 25
  • 98
  • 150
Jules
  • 1,071
  • 2
  • 18
  • 37
  • possible duplicate of [Injecting HttpContext in Ninject 2](http://stackoverflow.com/questions/3617447/injecting-httpcontext-in-ninject-2) – CAbbott Nov 30 '11 at 22:50

1 Answers1

2

Wherever you are setting up your dependencies:

kernel.Bind<HttpContext>().ToMethod(c => HttpContext.Current);

I have a bootstrapper class that does this with a RegisterServices method:

public static class NinjectMVC3
{
    private static readonly Bootstrapper bootstrapper = new Bootstrapper();

    /// <summary>
    /// Starts the application
    /// </summary>
    public static void Start()
    {
        DynamicModuleUtility.RegisterModule(typeof(OnePerRequestModule));
        DynamicModuleUtility.RegisterModule(typeof(HttpApplicationInitializationModule));
        bootstrapper.Initialize(CreateKernel);
    }

    /// <summary>
    /// Stops the application.
    /// </summary>
    public static void Stop()
    {
        bootstrapper.ShutDown();
    }

    /// <summary>
    /// Creates the kernel that will manage your application.
    /// </summary>
    /// <returns>The created kernel.</returns>
    private static IKernel CreateKernel()
    {
        var kernel = new StandardKernel();
        RegisterServices(kernel);
        return kernel;
    }

    /// <summary>
    /// Load your modules or register your services here!
    /// </summary>
    /// <param name="kernel">The kernel.</param>
    private static void RegisterServices(IKernel kernel)
    {            
        kernel.Bind<HttpContext>().ToMethod(c => HttpContext.Current);
    }
}
Dismissile
  • 32,564
  • 38
  • 174
  • 263