我正在通过添加IHttpModule使用cookie进行登录。该模块依赖于我的DbContext,它在Ninject配置中被设置为InRequestScope。但是,尽管我在SendAsync实现中使用了(MyContext)DependencyResolver.Current.GetService(typeof(MyContext));,但HTTP模块似乎获得了与请求的其余代码不同的DbContext。
发布于 2013-08-08 15:53:44
你需要使用ninject的web通用扩展名和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)
{
...
}
}https://stackoverflow.com/questions/18097813
复制相似问题