2011-11-30 25 views
0

傳遞參數,接口類我有一個類來保存這樣在ninject

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

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

我希望能夠注入會話對象在我MVC3應用程序不同的地方會議。 我有這個接口

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

我使用ninject到會話類綁定接口這樣

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

我的問題是如何的HttpContext參數傳遞到SessionService構造。

任何最受讚賞的指針。

感謝

+0

可能重複的[注入的HttpContext中Ninject 2](http://stackoverflow.com/questions/3617447/injecting-httpcontext-in-ninject-2) – CAbbott

回答

2

無論你在哪裏設置你的依賴:

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

我有一個引導程序類與RegisterServices方法做到這一點:

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); 
    } 
}