PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, September 13, 2022

[FIXED] How to determine if a NET Core class library is running in the context of a desktop or web application

 September 13, 2022     .net-core, cross-platform, dependency-injection     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing