【问题标题】:InRequestScope ObjectContext for IHttpModuleIHttpModule 的 InRequestScope ObjectContext
【发布时间】:2013-08-08 15:53:44
【问题描述】:

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

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

【问题讨论】:

  • 您是否尝试过使用构造函数注入而不是在依赖解析器上进行解析?
  • 构造函数注入不适用于IHttpModuleDelegatingHandler,因为它们在每个应用程序中被实例化一次,而不是每个请求一次。

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


【解决方案1】:

您需要 ninject Web 通用扩展和 ninject 的 webapi 扩展。在我们的代码中,它看起来像下面这样,甚至可以使用 Tor 注入:

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)
    {
        ...
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-20
    • 1970-01-01
    • 1970-01-01
    • 2011-05-28
    • 2020-02-21
    • 2011-10-18
    • 2011-01-25
    相关资源
    最近更新 更多