Search code examples
c#dependency-injectionconnection-stringnullreferenceexception

Do you have to add service in Startup for all DIs of a Connection String?


I am using a database in my application and thus I need access to my connection string which is stored in my appsettings.json file. It seems clunky to add a service a bunch of times in my Startup.cs file where I'm doing the same thing every time. Since I have a connection string that needs to be used in classes which are then used on Blazor pages, I attempted to make a connection string providing service:

public class ConnectionStringService
    {
        public string DataDB { get; set; }      
    }
//In Startup.cs
   services.Configure<ConnectionStringService>(Configuration.GetSection("ConnectionStrings"));
   services.AddScoped<ConnectionStringService>();
//I don't want a billion services.AddScoped<>(), one for every time I want to use a connection string, because it would get messy.

And attempt to use it like:

 public class SearchesTimeline
    {
        [Inject]
        private ConnectionStringService connectionStrings { get; }
        //private readonly ConnectionStringService connectionStrings;
        //public SearchesTimeline(IOptions<ConnectionStringService> options)
        //{
        //    connectionStrings = options.Value;
        //}

        public async Task<List<List<Timelineinfo>>> GetTimeline(string? current, int? dateChange, string? date)
        { 
            if (current != null && dateChange != null)
            {
                date = Convert.ToDateTime(current).AddDays((double)dateChange).ToString("yyyy-MM-dd");
            }
            //This line is being executed
            else if (date == null | string.IsNullOrWhiteSpace(Extensions.GetQueryParm("d")))
            {
                date = DateTime.Today.ToString("yyyy-MM-dd");
            }
            else
            {
                date = Extensions.GetQueryParm("d");
            }

            for (int i = 0; i < 7; i++)
            {
                //get data
                DataAccess data = new DataAccess();
                var query = "SELECT t.TimelineinfoId From timelineinfo t where t.date = " + dates[i].ToString("yyyy-MM-dd") + ";";
                dateData[i] = await data.LoadData<Timelineinfo, dynamic>(query, new { }, connectionStrings.DataDB);
            //Here, where I access connectionStrings.DataDB, I get the error
            }
            //more code stuff
        }
    }
//On the blazor page:
SearchesTimeline searches = new Searches.SearchesTimeline();

    [Parameter]
    public string? current { get; set; }
    [Parameter]
    public string? date { get; set; }

    protected override async Task OnInitializedAsync()
    {
        await searches.GetTimeline(current, 0, date);
    }
    public async Task NextWeek()
    {
        await searches.GetTimeline(current, +7, date);
    }
    public async Task PrevWeek()
    {
        await searches.GetTimeline(current, +7, date);
    }

But when I try to run this, I'm getting a NullReferenceException: "Object reference not set to an instance of an object." So this code isn't working.

Is there a way to configure one service for all my connection string needs, and use it in a way similar to above?


Solution

  • What I ended up doing was making a static function that would return the connection string wherever I needed it. I changed my Startup.cs file to contain:

     public static string ConnectionString { get; private set; }
    
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        //Add alongside whatever else you have in Configure()
        ConnectionString = Configuration["ConnectionStrings:DataDB"];
    }
    

    The function is really simple, just:

    public static string GetConnectionString()
    {
        return Startup.ConnectionString; //returns DataDB connection string
    }