0

我正在通过添加IHttpModule. 该模块依赖于 my DbContext,它设置InRequestScope在 Ninject 配置中。然而,似乎 HTTP 模块DbContext与请求的其余代码不同,即使我(MyContext)DependencyResolver.Current.GetService(typeof(MyContext));SendAsync实现中使用。

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

4

1 回答 1

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

}
于 2013-08-08T07:53:44.313 回答