If you wannt to use a helper class which signs in a user, you should make an extension method instead, which either wraps around IHttpContextAccessor
or HttpContext
itself.
public static class HttpContextExtensions
{
public static void SignInUser(this HttpContext context)
{
await context.Authentication.SignInAsync(..);
}
public static void SignInUser(this.IHttpContextAccessor contextAccessor)
{
// Calls the method from above
contextAccessor.HttpContext.SignInUser();
}
}
Or if you have a bigger dependency chain and require other injected services, convert it into a injectable class:
public class UserLogonService : IUserLogonService
{
private readonly IHttpContextAccessor contextAccessor;
public UserLogonService(IHttpContextAccessor contextAccessor)
{
if(contextAccessor==null)
throw new ArgumentNullException(nameof(contextAccessor));
this.contextAccessor = contextAccessor;
}
public void SingInUser()
{
contextAccessor.HttpContext.SignInUser();
}
}
and in Startup.Configure
method:
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddSingleton<IUserLogonService, UserLogonService>();
Now you can inject IUserLogonService
everywhere in your project via constructor, i.e.
public class MyController
{
private readonly IUserLogonService userLogon;
public MyController(IUserLoggonService userLogon)
{
this.userLogon = userLogon;
}
public async Task<IActionResult> Login()
{
await userLogon.SignInUser();
}
}
It's clean, decoupled and can easily be unit tested, which you can't do with a static helper class.