如何从 Blazor 应用程序中的类库访问连接字符串?

问题描述 投票:0回答:1

在我的解决方案中,我有三个项目:

  • 类库(业务逻辑层/数据访问)
  • Blazor WebAssembly 应用程序(客户端应用程序)
  • 控制台应用程序(客户端应用程序)

我的类库拥有所有业务逻辑:数据上下文接口模型存储库以及数据库作为Sqlite文件。

现在我想将连接字符串传递给这两个客户端项目。 据我所知,在 Blazor 应用程序中,您必须注册一项服务才能正确访问数据库。如何将连接字符串(在类库中描述)传递到 Blazor 应用程序中的

options.UseSqlite();
和控制台应用程序?如何重用类库中定义的选项而不是在 Blazor 应用程序中定义另一个选项?

在这方面,访问从类库到任何客户端应用程序的连接字符串的最佳方法是什么?在这种情况下,遵循 SOLID 原则的最佳实践是什么?

类库中的DataContext.cs

using Microsoft.EntityFrameworkCore;
using Schowek.Library.Models;

namespace Schowek.Library.Data
{
    public class DataContext : DbContext
    {
        public DataContext()
        {

        }
        public DataContext(DbContextOptions<DataContext> options) : base(options) { }

        public DbSet<Catalog>? Catalogs { get; set; } = null!;
        public DbSet<Item>? Items { get; set; } = null!;

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                optionsBuilder.UseSqlite("Data Source=./Data/app.db");
            }
        }
    }
}

Blazor 应用程序中的 Program.cs

using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using Microsoft.EntityFrameworkCore;
using Schowek.Client.BlazorWASM;
using Schowek.Library.Data;
using Schowek.Library.Interfaces;
using Schowek.Library.Repositories;

var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");

builder.Services.AddDbContext<DataContext>(options =>
{
    options.UseSqlite();
});
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
builder.Services.AddScoped<ICatalogRepository, CatalogRepository>();

await builder.Build().RunAsync();

类库中的appsettings.json

{
  "ConnectionStrings": {
    "DevelopmentConnection": "DataSource=./Data/app.db;Cache=Shared"
  }
}
c# .net asp.net-core blazor .net-7.0
1个回答
-1
投票

如果我正确理解了问题,并且您想在 ClassLibrary 和 Blazor 客户端应用程序之间共享连接字符串, 根据您的情况,在您的 Blazor 项目或每个人都使用的另一个公共项目中创建一个类。例如:名称为

'AppConfigurations'
且字符串属性名为
DevelopmentConnection
.

现在,在注册服务的

Program.cs
文件中,将
appsettings.json
文件添加到上面创建的“AppConfigurations.cs”中,您将能够解析该文件。

你可以像这样进行解析:


var configs = new AppConfigurations();
builder.Configuration.GetSection("ConnectionStrings").Bind(configs);
    
builder.Services.AddSingleton(configs);

现在

appsetting.json
文件中的连接字符串已加载到
'configs'
中,并注入到项目范围中 你可以使用。

© www.soinside.com 2019 - 2024. All rights reserved.