If you have been using .NET Core, then you know that Dependency Injection is rather important in this new ecosystem. Thankfully, the development team made it incredibly easy to use.
One common scenario that I have seen arise since its release, has been something to the extent of:
"How can I inject Identity or User information via D.I. in .NET Core?"
This could be a common use case for systems that require identity information for server-level transactions (e.g. when creating a new entity, you might want to know who performed this action or likewise if you wanted to audit who accessed a particular record in your system).
This post will cover implementing such services that you can easily use or extend within your applications; which you have probably tried already, but didn't work.
The most common place that you'll see developers go to access the current user might be as simple as the User.Identity property that is exposed from the HttpContext. However, if you are reading this post, I'm sure that you have attempted something like the following.
- // Example of a controller
- public FooController(FooContext context)
- {
- // Injecting your data context (a common-use case)
- _context = context;
- // Attempting to resolve the current user
- _user = HttpContext.User?.Identity?.Name;
- }
So, in order for us to actually access anything within the HttpContext, we will need to explicitly inject it. Thankfully, that isn't too difficult to do.
Building a Service to Inject the HttpContext
For D.I. to work, we will need to build a service that can inject the HttpContext that we need in the pipeline so that we can access the properties of it.
We can do this by creating a simple class that already injects that information into it, behind the scenes via a IHttpContextAccessor object, as seen below.
- public class UserResolverService
- {
- private readonly IHttpContextAccessor _context;
- public UserResolverService(IHttpContextAccessor context)
- {
- _context = context;
- }
- public string GetUser()
- {
- return await _context.HttpContext.User?.Identity?.Name;
- }
- }

Mohammed Deeb HammoudehPosted Dec 22, 2016, 2:39 AM
It is helpful , thanks Rion
Aleena SaviourPosted Nov 30, 2016, 8:47 AM
Good article...helpful...
Ananth GPosted Oct 21, 2016, 5:52 AM
Nice
Sandeep Singh ShekhawatPosted Oct 11, 2016, 9:43 PM
Love it :)