用于IHttpModule的InRequestScope ObjectContext

时间:2013-08-07 08:00:14

标签: c# asp.net-mvc-4 asp.net-web-api ninject

我正在使用Cookie添加IHttpModule进行登录。该模块依赖于我的DbContext,在Ninject配置中设置为InRequestScope。但是,即使我在DbContext实现中使用(MyContext)DependencyResolver.Current.GetService(typeof(MyContext));,HTTP模块似乎也会获得与请求的其余代码不同的SendAsync

如何在HTTP模块,DbContext和实际请求中获取DelegatingHandler的相同实例?

1 个答案:

答案 0 :(得分:1)

你需要ninject web公共扩展和ninject的webapi扩展。在我们的代码中,它看起来像以下一样,即使使用Ctor注入也可以使用:

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

    public static void Start()
    {
        ConfigureLogger();

        DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
        DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
        bootstrapper.Initialize(CreateKernel);
    }

    public static void Stop()
    {
        bootstrapper.ShutDown();
    }


    private static IKernel CreateKernel()
    {
        var kernel = new StandardKernel();
        RegisterServices(kernel);

        kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
        kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
        kernel.Bind<IHttpModule>().To<AuthenticationHttpModule>();

        return kernel;
    }

    private static void RegisterServices(IKernel kernel)
    {
        kernel.Load(Assembly.GetExecutingAssembly());
    }
}

,例如我们的自定义模块

public class AuthenticationHttpModule : IHttpModule
{
    private readonly IAuthenticationVerifier authenticateVerify;

    public AuthenticationHttpModule(IAuthenticationVerifier authenticateVerify)
    {
        this.authenticateVerify = authenticateVerify;
    }

    public void Dispose()
    {
    }

    public void Init(HttpApplication application)
    {
        application.AuthenticateRequest += this.OnAuthenticateRequest;
        application.EndRequest += this.OnEndRequest;
    }

    private void OnAuthenticateRequest(object source, EventArgs eventArgs)
    {
        var app = (HttpApplication)source;

        try
        {
            var user = this.authenticateVerify.DoAuthentication(app.Request);

            app.Context.User = user;
        }
        catch (InvalidCredentialException)
        {
            this.DenyAccess(app);
        }
    }

    private void OnEndRequest(object source, EventArgs eventArgs)
    {
        ...
    }

}