Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autofac register IHttpContextAccessor

I use autofac PropertiesAutowired approach (ASP.NET CORE). What I need is to get current user in class library project. How can I do it? I want something like this

public IHttpContextAccessor ContextAccessor{ get; set; }

and then to use it like

Context.HttpContext.User.Claims.First(i => i.Type == "NameIdentifier"

Is it possible to do or should I use something else for it?

like image 619
user3287801 Avatar asked Mar 12 '26 11:03

user3287801


1 Answers

Note: Below only works when registering Autofac with ASP.NET Core as described here or here.

If it is not required to use auto-wiring for properties I'd suggest you do the following

First, register the dependency as singleton (yes, it's not a problem, MS does it too)

builder.RegisterType<HttpContextAccessor>()
   .As<IHttpContextAccessor>()
   .SingleInstance();

Assuming your class is called MyClass inject it via constructor

public MyClass(IHttpContextAccessor httpContextAccessor)
{
   ContextAccessor = httpContextAccessor;
}

Now you are good to go! I am sure you can make it work with property-auto-wiring but I am not familiar with that approach.

As a side-note:

If you want to retrieve the information of the authenticated user, I heard and have read that it is recommended to write something like an ApplicationUser class that wraps the underlying framework logic.

I implemented something similar here that also uses IHttpContextAccessor to retrieve required claims + I am registering the accessor with autofac as well. Only difference is that I am using constructor-injection.

I hope that helps you!

like image 60
alsami Avatar answered Mar 16 '26 09:03

alsami



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!