Initialize a singleton from cookies for a ASP.NET Core Razor project

18 views Asked by At

I'm totally NEW into developing web applications with ASP.NET 8 and Razor and I have spent several hours trying to port my Windows App to web. I simply cannot wrap my head around how to make something very simple work:

In my app, I have a appSetting class that is read from a configuration file. This setting it used all over my application. Now I want something similar for my web app, but I keep running into all sorts of things I do not get.

I have made the class 'appSetting' and added it as a singleton in Program.cs:

builder.Services.AddSingleton<AppSetting>();

Then I think that I need to initialize it somewhere, and I have tried to do this in the 'index.cshtml.cs' file.

private readonly AppSetting _appSetting;

public string appVersion => _appSetting.version;

public IndexModel(ILogger<IndexModel> logger)
{
   _logger = logger;
   _appSetting = new AppSetting();
}

In the constructor of my class, I try to read the cookie, but this just throws a runtime error: System.NullReferenceException: 'Object reference not set to an instance Of an object.'

public AppSetting()
{
   var cookies = Request.Cookies["version"];
}

I simply do not know how to achieve what I want.

Thanks in advance

Lars Bo

1

There are 1 answers

0
Red Star On

I use this approach to achieve this in my apps

 using Microsoft.Extensions.Options;

 public static class IocExtensions
    {
        public static void AddConfiguration<TInterface, T>(this IServiceCollection services, string? configurationName = null)
            where T : class, TInterface
        {
            AddConfiguration<T>(services, configurationName);
            RegisterByType<TInterface, T>(services);
        }
    
        public static void AddConfiguration<T>(this IServiceCollection services, string? configurationName = null)
            where T : class
        {
            services.AddOptions<T>()
                    .BindConfiguration(configurationName ?? typeof(T).Name)
                    .ValidateDataAnnotations()
                    .ValidateOnStart();
    
            RegisterByType<T, T>(services);
        }
    
        private static void RegisterByType<TInterface, T>(IServiceCollection services)
            where T : class, TInterface
        {
            services.AddSingleton(typeof(TInterface), provider => provider.GetRequiredService<IOptions<T>>().Value);
        }
    } 

That's how i use it

builder.Services.AddConfiguration<IMyConfiguration, MyConfiguration>();

And that's models

public interface IMyConfiguration
{
   string MyProp { get; }
}

public class MyConfiguration: IMyConfiguration
{
    public required string MyProp { get;init; }
}

In order to parse everything you need to have this in appsettings.json

"MyConfiguration": {
    "MyProp": ""
  }

That's how i use it, there is some simpler solutions, i found this in stack overflow