将参数传递给对象中的接口类
本文关键字:接口 对象 参数传递 | 更新日期: 2023-09-27 18:16:30
我有一个类来进行这样的会话
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构造函数。
任何提示都非常感谢。
谢谢
无论您在哪里设置依赖项:
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);
}
}