Mocking Systems Resources in C#/ASP.NET

Static System Resources

public interface IDateTimeService
{
DateTime UtcNow { get; }
}

public class DateTimeService : IDateTimeService
{
public DateTime UtcNow => DateTime.UtcNow;
}

ASP.NET Context

public interface IPrincipalService
{
int UserId { get; }
}

public class PrincipalService : IPrincipalService
{
private readonly IHttpContextAccessor _httpContextAccessor;

public PrincipalService(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}

public int UserId
{
get
{
var claimsPrincipal = _httpContextAccessor.HttpContext?.User;
if (claimsPrincipal == null)
throw new MissingClaimsPrincipalException();

return int.Parse(claimsPrincipal.FindFirst(ClaimTypes.NameIdentifier)?.Value ?? "", CultureInfo.CurrentCulture);
}
}
}

I’m a Full-stack Software Engineer and Architect living and working in the Portland, OR Metro area, specializing in .NET and web technologies.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store