How to get connection string without DbOptions?

Viewed 195

I'm a project that doesn't need DbContext class, and I'm using BlobStorage DB on appsettings.json

This is my appsettings.json

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

and I configure on Startup.cs class, without options, because I don't need DbContext right now

_configuration.GetConnectionString("StorageConnectionString");

But I need to call my connection string on my BlobStorageService class without pass connection string name (because is already on appsettings.json).

The question is: How I can call connectionString on Service class without pass the connection string name?

2 Answers

It works if I use

 Configuration.GetConnectionString("StorageConnectionString"); 

Getting IConfiguration and doing dependency injection inside my BlobStorageService.

How are you registering your BlobStorageService? If you're already retrieving your connection string within Startup.cs, you can always register your BlobStorageService with a string dependency to be used within the service at runtime.

In your BlobStorageService, you can require a string to be injected when the service is requested:

public class BlobStorageService : IBlobStorageService
{
    private readonly string _connectionString;

    public BlobStorageService(string connectionString)
    {
        _connectionString = connectionString;

        // Do whatever storage client initialization is required by the SDK...
    }
}

Then, in your Startup.cs, register your dependency with the connection string you've already retrieved at application startup:

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

    // ...other dependencies
}
Related