Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpContextAccessor, IPrincipal and ServiceCollection

Is there a way that I could implement next behaviour?

public static void Configure(IServiceCollection services) {
    services.AddScoped(typeof(Func<IPrincipal>), ???);
    services.AddInstance(typeof(Func<IPrincipal>), ???);
}

1. Does not work:

Func<IServiceProvider, IPrincipal> getPrincipal = 
    (sp) => sp.GetService<IHttpContextAccessor>().HttpContext.User;

services.AddScoped(
    typeof(Func<IPrincipal>), 
    getPrincipal);  

2. Does not work:

var builder = services.BuildServiceProvider();

services.AddInstance(
    typeof(Func<IPrincipal>),
    builder.GetService<IHttpContextAccessor>().HttpContext.User);
like image 955
Maxim Zhukov Avatar asked Oct 19 '25 01:10

Maxim Zhukov


1 Answers

Func<IServiceProvider, IPrincipal> getPrincipal = 
    (sp) => sp.GetService<IHttpContextAccessor>().HttpContext.User;

services.AddScoped(
    typeof(Func<IPrincipal>), 
    getPrincipal); 

You are trying to resolve the delegate, but I assume you want to resolve IPrincipal instead. I assume your service may look like this

public class MyService : IMyService 
{
    public MyService(IPrincipal principal) 
    {
        ...
    }
}

If so, then your registration is wrong. You are registering Func<IPrincipal> but expecting IPrincipalwhich isn't registered.

You should either register the factory for IPrincipal or (less recommended imho) inject the Func<IPrincipal> into your service.

Func<IServiceProvider, IPrincipal> getPrincipal = 
    (sp) => sp.GetService<IHttpContextAccessor>().HttpContext.User;

services.AddScoped<IPrincipal>(getPrincipal); 

or shorter

services.AddScoped<IPrincipal>(
    (sp) => sp.GetService<IHttpContextAccessor>().HttpContext.User
); 

or

public class MyService : IMyService 
{
    priate IPrincipal principal;
    public MyService(Func<IPrincipal> principalFactory) 
    {
        this.principal = principalFactory();
    }
}
like image 99
Tseng Avatar answered Oct 20 '25 16:10

Tseng



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!