2013-08-07 2 views
0

IHttpModule을 추가하여 쿠키를 사용하여 로그인하고 있습니다. 모듈은 DbContext에 종속성을 가지며 Ninject 구성에서 InRequestScope으로 설정됩니다. 그러나 SendAsync 구현에서 (MyContext)DependencyResolver.Current.GetService(typeof(MyContext));을 사용하더라도 HTTP 모듈이 나머지 코드와 비교하여 DbContext이되는 것 같습니다.InRequestScope IHttpModule 용 ObjectContext

DbContext의 동일한 인스턴스를 HTTP 모듈 DelegatingHandler 초 및 실제 요청으로 가져올 수 있습니까?

+0

은 종속성 해결에 해결하는 대신 생성자 주입을 사용하여 시도? –

+0

생성자 삽입은'IHttpModule'과'DelegatingHandler'에 대해서는 작동하지 않습니다. 왜냐하면 그것들은 요청 당 한 번이 아니라 앱마다 한번 인스턴스화되기 때문입니다. –

답변

1

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

}