【问题标题】:.Net Core And EntityFrameworkCore.Net Core 和 EntityFrameworkCore
【发布时间】:2018-09-28 12:02:09
【问题描述】:

我正在尝试学习 .Net 核心。

我有 2 个项目:

  1. .Net Core Web api 项目
  2. DLL .NetCore 项目包含我的工作单元(实体框架)

我的问题:

  1. 如何从 appsettings.json 传递连接字符串 到我的 DLL

    我有 startup.cs 配置,但我不知道如何使用它来访问我的 appsettings.json

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }
    

    startup.cs 中有 services.AddDbContext

     
      services.AddDbContext(options => 
         options.UseSqlServer(
         Configuration.GetConnectionString("DefaultConnection")))

    但我不想使用 services.AddDbContext,因为它是实体框架的一对,如果我必须更改为其他 ORM,我必须更改 这段代码也是。

  2. 其他问题如何负责解密连接 字符串。

    • a : webapi 必须解密为连接字符串并传递给 DLL (工作单位)

    • b:或工作单元必须解密连接字符串

  3. 如果我有另一个项目(即桌面应用程序)如何 使用 DLL(工作单元)我是否还必须放置连接 我的桌面应用程序的 appsettings 中的字符串? (就如 一种重复? )

【问题讨论】:

  • 这方面有什么更新吗?

标签: c# .net-core entity-framework-core unit-of-work


【解决方案1】:

我不想使用 services.AddDbContext 因为是一对实体框架

所以你需要做的是在你的 EF 项目中创建一个扩展方法来包装这个调用,这样对 EF 的依赖就会保留在 EF 项目中,如下所示:

public static IServiceCollection AddDatabase<TContext>( this IServiceCollection serviceCollection, Action<DbContextOptionsBuilder> optionsAction, string connectionString)
{
    options.UseSqlServer(connectionString))
}

然后从您的启动代码中调用它:

services.AddDatabase(Configuration.GetConnectionString("DefaultConnection"));

这将解决您的依赖问题。

关于 2: 见这里:Encrypted Configuration in ASP.NET Core

关于3:那么其他项目需要调用AddDatabase方法并传入连接字符串,所以EF项目永远不会知道从哪里得到它,它是始终提供。

【讨论】:

    【解决方案2】:

    你可以这样做:

    public BooksContext(string connectionString): this(GetOptions(connectionString))
    { }
    
    private static DbContextOptions GetOptions(string connectionString)
    {
        return SqlServerDbContextOptionsExtensions.UseSqlServer(new DbContextOptionsBuilder(), connectionString).Options;
    }
    

    【讨论】:

      【解决方案3】:

      你可以像这样获取 in Stratup.cs 文件。

      using Microsoft.AspNetCore.Hosting;
      using Microsoft.Extensions.Configuration;
      
      
      private readonly IConfigurationRoot _appConfiguration;
      private readonly IHostingEnvironment _hostingEnvironment;
      
      public Startup(IHostingEnvironment env)
      {
          _hostingEnvironment = env;
          _appConfiguration = env.GetAppConfiguration();
      }
      

      获取 ConnectionString 的代码:

      string connectionString = _appConfiguration["ConnectionStrings:Default"];
      

      appsettings.json

      {
        "ConnectionStrings": {
          "Default": "Server=YourDBAddress; Database=YourDB; Trusted_Connection=True;"
        }
        ...
      }
      

      其他点可以参考@Jamie Rees 的回答。

      【讨论】:

        猜你喜欢
        • 2021-04-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-07-29
        • 2016-10-07
        • 2020-07-13
        • 2017-04-15
        相关资源
        最近更新 更多