Search code examples
c#dependency-injectionblazornullreferenceexception

Navigation Manager NullReferenceException


I am attempting to get the query string from a URL as suggested here, but I'm getting a NullReferenceException. The only difference between my code and the code in the linked post is that mine is static, and I don't see how that could cause an error.

public static class Extensions
    {
        //Other helper methods

        [Inject]
        public static NavigationManager MyNavigationManager { get; set; }

        public static string GetQueryParm(string parmName)
        {
            //Null Reference Exception is called on the line below
            var uriBuilder = new UriBuilder(MyNavigationManager.Uri);           
            var q = System.Web.HttpUtility.ParseQueryString(uriBuilder.Query);
            return q[parmName] ?? "";
        }
    }

I am calling this method like:

 else if (date == null | string.IsNullOrWhiteSpace(Extensions.GetQueryParm("d")))
 {
     date = DateTime.Today.ToString("yyyy-MM-dd");
 }

Solution

  • You cannot @inject or [Inject] into a static class. The MyNavigationManager property will never be assigned to.

    So forget about making this an extension method and inject it into your blazor page.