concept IUserContext in category dependency injection

appears as: IUserContext
Dependency Injection

This is an excerpt from Manning's book Dependency Injection.

Besides an IProductRepository, the ProductService constructor requires an instance of IUserContext:

As we described, IPrincipal is 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 own IUserContext Abstraction instead of letting the domain layer depend on IPrincipal. This does mean, however, that we have to create an Adapter implementation that allows translating calls from this application-specific IUserContext Abstraction to calls to the application framework.

Figure 3.11 Both IUserContext and IProductRepository are part of the domain layer, because ProductService “owns” them.

03-11.eps

3.1.4 Implementing an ASP.NET Core–specific IUserContext Adapter

The 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 IUserContext is 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 our IUserContext implementation.

The following listing shows a possible IUserContext implementation for an ASP.NET Core application.

Listing 3.12 IUserContext implementation for ASP.NET Core
public class AspNetUserContextAdapter : IUserContext
{
    private static HttpContextAccessor Accessor = new HttpContextAccessor();

    public bool IsInRole(Role role)
    {
        return Accessor.HttpContext.User.IsInRole(role.ToString());
    }
}