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