I am building a class library for an MVC app and need to read data from the appsettings.json file but am running into a NullReferanceExpecption. This this possible to do and if so what am I missing?
Appsettings.json file:
{"AppSettings": {"AppVersion": "2.0.0" },"Data": {"JobSightDatabase": { } } }
Startup.cs:
public class Startup { public IConfigurationRoot Configuration { get; set; } public Startup(IHostingEnvironment env) { //Set up configuration sources. var builder = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); Configuration = builder.Build(); } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddCaching(); services.AddSession(o => { o.IdleTimeout = TimeSpan.FromSeconds(10); }); services.Configure<AppSettings>(Configuration.GetSection("AppSettings")); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseExceptionHandler("/Error/ServerError"); app.UseIISPlatformHandler(); app.UseSession(); app.UseStaticFiles(); app.UseStatusCodePagesWithReExecute("/Error/PageNotFound"); app.UseMvc(); } // Entry point for the application. public static void Main(string[] args) => WebApplication.Run<Startup>(args); }
test.cs:
public class test { protected static IOptions<AppSettings> _AppSettings; public test(IOptions<AppSettings> AppSettings) { _AppSettings = AppSettings; } public static string GetAppVersion() { return _AppSettings.Value.AppVersion; } }
That is the code I am using. When I go into my class and do something like
var AppVersion = test.GetAppVersion();
I get the NullReferanceException error. I have seen a few blogs that show how to do this in a controller (in fact they are how I got this far) but none for class library, help please!