Unable to resolve service while trying to activate Startup

342 Views Asked by At

I'm trying to access IHttpContextAccessor And IUserRetrieve services within my Events.OnSignedIn method in my Configure Services.

The below line of code worked in an older version of .net core however, in .NET CORE 5.0 this no longer works.

Any Suggestions?

            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);
                }


             
            };

enter image description here

2

There are 2 best solutions below

0
On BEST ANSWER

Reference: Services injected into Startup

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

  • IWebHostEnvironment
  • IHostEnvironment
  • IConfiguration

Note that CookieSignedInContext provides access to the current request's HttpContext which can be used to resolve request services as needed.

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;

    //...
}
0
On

If you need to access dependencies within a cookie event, you should register an options.EventsType. eg;

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

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