Startup.Configure中的ASP.NET核心依赖注入

ale*_*esc 4 asp.net configuration dependency-injection startup asp.net-core

我正在使用Cookie中间件来验证用户身份.我一直在关注这个官方教程.

在我的Startup课程中,我的Configure方法摘录如下:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
  // ...

  // Cookie-based Authentication
  app.UseCookieAuthentication(new CookieAuthenticationOptions()
  {
    AuthenticationScheme = CookieAuthenticationDefaults.AuthenticationScheme,        
    AutomaticAuthenticate = true,
    AutomaticChallenge = true,
    Events = new CustomCookieAuthenticationEvents(app),
  });

  // ...
}
Run Code Online (Sandbox Code Playgroud)

所述CustomCookieAuthenticationEvents类的定义如下:

public class CustomCookieAuthenticationEvents : CookieAuthenticationEvents
{
  private IApplicationBuilder _app;
  private IMyService _myService = null;
  private IMyService MyService
  {
    get
    {
      if(_myService != null)
      {
        return _myService;
      } else
      {
        return _myService = (IMyService) _app.ApplicationServices.GetService(typeof(IMyService));
      }
    }
  }

  public CustomCookieAuthenticationEvents(IApplicationBuilder app)
  {
    _app = app;
  }

  public override async Task ValidatePrincipal(CookieValidatePrincipalContext context)
  {
    string sessionToken = context.Principal.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Sid)?.Value;
    LogonSession response = null;

    var response = await MyService.CheckSession(sessionToken);

    if (response == null)
    {
      context.RejectPrincipal();
      await context.HttpContext.Authentication.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

由于依赖注入不可用Startup.Configure(服务甚至没有在那时注册),我做了一些解决方法:

  1. 将IApplicationBuilder服务传递给CustomCookieAuthenticationEvents该类
  2. IMyService在只读属性内获取第一个请求(单例模式)

TL;博士

我的解决方案有效,但它很难看.没有涉及依赖注入,因为那时不可能.

问题的实质是我必须实例化CustomCookieAuthenticationEvents.至于我已经阅读过源代码,没有办法解决这个问题,因为UseCookieAuthentication如果我省略options参数会引发异常.

任何建议如何使我当前的解决方案更好

小智 11

在Startup.Configure()之前调用Startup.ConfigureServices()(有关更多信息,请参阅https://docs.microsoft.com/en-us/aspnet/core/fundamentals/startup).因此,当时可以使用依赖注入;)
因此,您可以在配置方法中解决您的依赖关系,如下所示:

app.ApplicationServices.GetRequiredService<CustomCookieAuthenticationEvents>()
Run Code Online (Sandbox Code Playgroud)

  • 这种方法使用服务定位器模式,您不需要这样做,您只需将您需要的内容添加到Startup.Configure方法签名中,它就会被注入到方法中 (4认同)