Use Dependency Injection In Static Class With .Net Core

We may face circumstances where we want to resolve a dependency inside a static class, but with the static class, we are restricted to a static constructor which is not supported for the .NET core to work for Constructor Injection.

So, today we will see how we can handle these kinds of operations, so we can achieve Dependency Injection with static classes in .NET Core.

There is simple logic if we cant use a constructor with the static class we can create one method in which we can pass dependency while run time. to do that we will use Startup.cs file and call that method and pass dependency from there.

For example, I want to use IHttpContextAccessor in my static class namely JWTClaimHelper. so I will create one method namely JWTClaimHelperConfigure instead of consturtor.

It will look like below

public static class JWTClaimHelper
   {
       private static IHttpContextAccessor _context;

       public static void JWTClaimHelperConfigure(IHttpContextAccessor context)
       {
           _context = context;
       }
   }

 

Now I’ll call the below method from Configure method inside the Startup file and pass dependency as a parameter.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{ 
  JWTClaimHelper.JWTClaimHelperConfigure(app.ApplicationServices.GetService<IHttpContextAccessor>());
}

Now I can use this dependency in JWTClaimHelper class.

JWTClaimHelper class will look like below.

public static class JWTClaimHelper
    {
        private static IHttpContextAccessor _context;

        public static void JWTClaimHelperConfigure(IHttpContextAccessor context)
        {
            _context = context;
        }


        public static string GetClaimValueFromType(string claimType)
        {
            ClaimsIdentity identity = _context.HttpContext.User.Identity as ClaimsIdentity;
            if (identity != null)
            {
                Claim claimData = identity.Claims.FirstOrDefault(x => x.Type.ToLower() == claimType.ToLower());
                if (claimData != null)
                {
                    return claimData.Value;
                }
            }
            return null;
        }
    }

And done, we can now enjoy the more definite syntax of the extension methods, along with dependency injection.

hope you guys found something useful. Please give your valuable feedback/comments/questions about this article. Please let me know how you like and understand this article and how I could improve it. If you like this blog you can buy me Pizza.

Submit a Comment

Your email address will not be published. Required fields are marked *

Footer Logo

Subscribe

Select Categories