您是否必须在 Startup 中为连接字符串的所有 DI 添加服务?

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

我在我的应用程序中使用了一个数据库,因此我需要访问存储在我的 appsettings.json 文件中的连接字符串。在我的 Startup.cs 文件中多次添加服务似乎很笨拙,我每次都在做同样的事情。由于我有一个连接字符串需要在 类 中使用,然后在 Blazor 页面上使用,因此我尝试创建一个提供服务的连接字符串:

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.

并尝试像这样使用它:

 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);
    }

但是当我尝试 运行 时,我收到 NullReferenceException:“对象引用未设置为对象的实例。”所以这段代码不起作用。

有没有办法为我所有的连接字符串需求配置一个服务,并以类似于上面的方式使用它?

   services.Configure<ConnectionStringService>(Configuration.GetSection("ConnectionStrings"));

在此行之后,您不再需要将类型添加到您的 DI。您可以使用 IOptions<> 接口获取该值。像这样:

[Inject] private IOptions<ConnectionStringService> connectionStrings { get; }

然后您可以通过访问对象的值 属性 来使用它:

connectionStrings.Value

我最终做的是创建一个静态函数,它可以 return 在我需要的任何地方使用连接字符串。我将 Startup.cs 文件更改为包含:

 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"];
}

功能真的很简单,就是:

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