InRequestScope ObjectContext for IHttpModule

本文关键字:IHttpModule for ObjectContext InRequestScope | 更新日期: 2023-09-27 18:26:39

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

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

InRequestScope ObjectContext for IHttpModule

你需要 ninject web common extension 和 webapi extension for ninject。在我们的代码中,它如下所示,甚至可以使用 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)
    {
        ...
    }
}