Search code examples
c#asp.net-coreappsettingsconstructor-injection

Get appsettings.json values without a constructor call in C# .Net Core 3.0


I have a class that came from an older pre .NET Core project and I'm trying to get it to read appsettings.json data. The catch is that it gets called in a way that does not appear to evoke a constructor, so the usual IOptions<AppSettings> constructor injection approach does not work.

The class is called from this method:

 private static string GetItemUrl(string language, string itemId)
    {
        return LinkHelp.Instance.Builder.BuildEditItemUrl(language, itemId);
    }

And that flows right into the following method:

private LinkHelp()
    {
        // Various attempts at getting a config setting here
        var linkBuilderoptions = new ContentManagementHelpersOptions() { ProjectId = projectId };
        Builder = new LinkBuil(linkBuildoptions);         
    }

The method did use the old pre-core AppSettingProvider.ProjectId method to get the project Id from a web.config:

var projectId = AppSettingProvider.ProjectId.ToString() ?? AppSettingProvider.DefaultProjectId.ToString();

Do I need to just add a web.config to the project and continue using the old method? Or is there a way to make this work with .Net Core 3.0?


Solution

  • This was one of those issues where you leave on a Friday after a long week and the simple answer doesn't come to you until after the weekend. Oh well.

    Configuration Injection didn't work on the LinkHelp() class - and the project already has a configuration defined. But all that was needed was to make a few small changes to pass the configuration on from the calling class to the receiving class.

    public LinkHelp(string projectId)
        {
            var linkBuilderoptions = new ContentManagementHelpersOptions() { ProjectId = projectId };
            Builder = new LinkBuil(linkBuildoptions);         
        }
    

    And then call that class in a slightly new way (this class already has access to the configs):

    private static string GetItemUrl(string language, string itemId)
    {
        projectId = ProjectOptions.OptionsList.ProjectId;
        var editLink = LinkHelp(propjectId).Instance.Builder.BuildEditItemUrl(language, itemId);
        return editLink
    }
    

    And that appears to have worked. It didn't require too many additional changes.