Issue
I have a .NET Core class library that provides functionality which can be used both by desktop and web applications. I would like to support as many of the platforms supported by .NET Core as possible.
When running in the context of a web application, I want the library to be able to detect the domain on which the application is hosted. Normally, I would do this using the HttpContext.Request
object, making the context available by injecting IHttpContextAccessor
. However, a desktop application has no HttpContext
.
Is there any way of injecting a service so that the reference is null in the consumer when it cannot be supplied?
Solution
So, in the end, in dependency injection configuration, I tested to see if the default AspNet Core HttpContextAccessor
was present, and if not, I pass in a fake object with a null HttpContext.
public void ConfigureServices(IServiceCollection services)
{
...
var accessorType = GetAccessorType() ?? typeof(NullOpHttpAccessor);
services.TryAddSingleton(typeof(IHttpContextAccessor), accessorType);
...
}
private static Type GetAccessorType()
{
var interfaceType = typeof(IHttpContextAccessor);
var excludedNames = new[] { "IHttpContextAccessor", "NullOpHttpAccessor" };
var type = AppDomain.CurrentDomain.GetAssemblies()
.AsEnumerable()
.SelectMany(a => a.GetTypes())
.FirstOrDefault(t => !excludedNames.Contains(t.Name) &&
interfaceType.IsAssignableFrom(t));
return type;
}
internal class NullOpHttpAccessor : IHttpContextAccessor
{
public HttpContext HttpContext { get => null; set => value = null; }
}
Then, in my library, I inject HttpContextAccessor
, test to see if the context is null, and proceed accordingly.
internal string DoStuff()
{
if (HttpContextAccessor.HttpContext == null)
{
return GetMacAddress();
}
return HttpContextAccessor.HttpContext.Request.Host.ToString();
}
Answered By - Paul Taylor Answer Checked By - Mildred Charles (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.