Home > Back-end >  .Net Core 6 Static Property for library version
.Net Core 6 Static Property for library version

Time:07-14

Requirement - Need to add version information to all api responses. .Net 6 / WebApi / C#

Possible Solution - Added a custom middleware to add version information to all api responses. In this middleware, I am using reflection to get assembly version, and adding it to header.

Query - I do not want to continually use reflection for all api responses. If I can just get the information once, and then re-use it for all responses, that would save me a lot of reflection operations. Below is my middleware code,

public class CustomHeaderMiddleware
{
    private readonly RequestDelegate _next;

    public CustomHeaderMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        context.Response.Headers.Add("Version", Assembly.GetExecutingAssembly().GetName().Version.ToString());
        await _next(context);
    }
}

But where I am stuck is, how to do so effectively? Add a static class somewhere, and then use it? Like we do with extensions. Is there a possible way to do this in program.cs?

Any suggestions?

CodePudding user response:

Keeping it simple, add a Lazy<> static field to your middleware, and access it from your middleware.

Something like

public class CustomHeaderMiddleware
{
    private static Lazy<string> _version = new Lazy<string>(GetVersion);

    private readonly RequestDelegate _next;

    public CustomHeaderMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        context.Response.Headers.Add("Version", _version.Value);
        await _next(context);
    }

    private static string GetVersion() => 
        Assembly.GetExecutingAssembly().GetName().Version.ToString();
}

Because it's lazy, the value will only be calculated once, on first access to the middleware. This guarantees the reflection cost is only paid once. The GetVersion() local function itself must be static.

You could move the GetVersion() code to program.cs, call it during startup, and instead set a static Version property on the middleware, but that has the drawback of violating encapsulation, and having two places to go for maintenance.

  • Related