concept IUserContext in category dependency injection

This is an excerpt from Manning's book Dependency Injection.
Besides an
IProductRepository, theProductServiceconstructor requires an instance ofIUserContext:
As we described,
IPrincipalis generic in nature. The Dependency Inversion Principle instead guides us towards defining Abstractions tailored for our application’s special needs. That’s why we define our ownIUserContextAbstraction instead of letting the domain layer depend onIPrincipal. This does mean, however, that we have to create an Adapter implementation that allows translating calls from this application-specificIUserContextAbstraction to calls to the application framework.Figure 3.11 Both
IUserContextandIProductRepositoryare part of the domain layer, becauseProductService“owns” them.![]()
3.1.4 Implementing an ASP.NET Core–specific
IUserContextAdapterThe last concrete implementation missing is that of
IUserContext. In web applications, information about a user who issues a request is usually passed on to the server with each request. This information is relayed using cookies or HTTP headers. How we retrieve the identity of the current user is highly dependent on the framework we use. This means that we’ll need a completely different implementation when building an ASP.NET Core application compared with, for instance, a Windows service.The implementation of our
IUserContextis framework specific. We want neither our domain layer nor our data layer to know anything about the application framework. That would make it impossible to use those layers in a different context. We need to implement this elsewhere. The UI layer, therefore, is an ideal place for ourIUserContextimplementation.The following listing shows a possible
IUserContextimplementation for an ASP.NET Core application.Listing 3.12
IUserContextimplementation for ASP.NET Corepublic class AspNetUserContextAdapter : IUserContext { private static HttpContextAccessor Accessor = new HttpContextAccessor(); public bool IsInRole(Role role) { return Accessor.HttpContext.User.IsInRole(role.ToString()); } }