ninject 웹 공통 확장 프로그램과 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)
{
...
}
}
은 종속성 해결에 해결하는 대신 생성자 주입을 사용하여 시도? –
생성자 삽입은'IHttpModule'과'DelegatingHandler'에 대해서는 작동하지 않습니다. 왜냐하면 그것들은 요청 당 한 번이 아니라 앱마다 한번 인스턴스화되기 때문입니다. –