【问题标题】:How to get connection string without DbOptions?如何在没有 DbOptions 的情况下获取连接字符串?
【发布时间】:2021-02-09 20:22:25
【问题描述】:

我是一个不需要 DbContext 类的项目,我在 appsettings.json 上使用 BlobStorage DB

这是我的 appsettings.json

{
  "ConnectionStrings": {
    "StorageConnectionString": "Connection"
 }

我在 Startup.cs 类上配置,没有选项,因为我现在不需要 DbContext

_configuration.GetConnectionString("StorageConnectionString");

但是我需要在我的 BlobStorageService 类上调用我的连接字符串而不传递连接字符串名称(因为已经在 appsettings.json 上)。

问题是:如何在不传递连接字符串名称的情况下在 Service 类上调用 connectionString?

【问题讨论】:

  • 返回空值。如果我使用 Configuration.GetConnectionString("StorageConnectionString");但我需要获取 IConfiguration 并在我的 BlobStorageService 中进行依赖注入,并且我已经在 Startup.class 上完成了这项工作。

标签: .net connection-string blobstorage


【解决方案1】:

如果我使用它会起作用

 Configuration.GetConnectionString("StorageConnectionString"); 

在我的 BlobStorageService 中获取 IConfiguration 并进行依赖注入。

【讨论】:

    【解决方案2】:

    您如何注册您的BlobStorageService?如果您已经在 Startup.cs 中检索连接字符串,则始终可以使用字符串依赖项注册您的 BlobStorageService,以便在运行时在服务中使用。

    在您的BlobStorageService 中,您可以要求在请求服务时注入一个字符串:

    public class BlobStorageService : IBlobStorageService
    {
        private readonly string _connectionString;
    
        public BlobStorageService(string connectionString)
        {
            _connectionString = connectionString;
    
            // Do whatever storage client initialization is required by the SDK...
        }
    }
    

    然后,在您的 Startup.cs 中,使用您在应用程序启动时已检索到的连接字符串注册您的依赖项:

    public void ConfigureServices(IServiceCollection services)
    {
        var yourConnectionString = Configuration.GetConnectionString("StorageConnectionString");
                
        // Register with the appropiate service lifetime
        services.AddTransient<IBlobStorageService>(_ => new BlobStorageService(yourConnectionString));
    
        // ...other dependencies
    }
    

    【讨论】:

    • 所以,我使用的是 azure blob 和服务总线服务。如何使用多个 ConnectionString 做到这一点? (每个服务都提供一个特定的主连接)。
    猜你喜欢
    • 2011-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多