尝试激活启动时无法解析服务

Unable to resolve service while trying to activate Startup

我试图在配置服务的 Events.OnSignedIn 方法中访问 IHttpContextAccessor 和 IUserRetrieve 服务。

下面的代码行在旧版本的 .net core 中有效,但是在 .NET CORE 5.0 中这不再有效。

有什么建议吗?

            o.Events.OnSignedIn = async ctx =>
            {
                var claims = ctx.Principal;

                var user = Dependency.Resolve<IUserRetrieveService>().ByUsername(ctx.Principal.Identity.Name) as UserDefinition;
                var remoteIpAddress = Dependency.Resolve<IHttpContextAccessor>().HttpContext.Connection.RemoteIpAddress;
                if (remoteIpAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)
                {
                    remoteIpAddress = System.Net.Dns.GetHostEntry(remoteIpAddress).AddressList
                    .First(x => x.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork);
                }


             
            };

参考:Services injected into Startup

Only the following services can be injected into the Startup constructor when using the Generic Host (IHostBuilder):

  • IWebHostEnvironment
  • IHostEnvironment
  • IConfiguration

请注意,CookieSignedInContext 提供对当前请求的 HttpContext 的访问,可用于根据需要解析请求服务。

o.Events.OnSignedIn = async ctx => {
    var claims = ctx.Principal;
    IServiceProvider services = ctx.HttpContext.RequestServices;
    var user = services.GetService<IUserRetrievService>().ByUsername(ctx.Principal.Identity.Name) as UserDefinition;
    var remoteIpAddress = ctx.HttpContext.Connection.RemoteIpAddress;

    //...
}

如果您需要访问 cookie 事件中的依赖项,您应该注册一个 options.EventsType。例如;

services.AddSingleton<MyEvents>();
services.ConfigureApplicationCookie(options => {
        options.EventsType = typeof(MyEvents);
    });

public class MyEvents : CookieAuthenticationEvents{
    public MyEvents (... dependencies here...){}
    ...
}