configurationblazor-server-sideappsettingsasp.net-core-8

ASP.NET Core 8 Blazor Server App - A suitable constructor could not be located


I have tried numerous approaches, unsuccessfully, to get the connection string from appsettings.json. If this is not the best approach, what approach would work?

Runtime error:

System.InvalidOperationException: A suitable constructor for type 'App.Services.DataService' could not be located. Ensure the type is concrete and all parameters of a public constructor are either registered as services or passed as arguments. Also ensure no extraneous arguments are provided.

appsettings.json:

{
    "ConnectionStrings": {
        "Database1": "Server=_____.____.____;Database=______;Trusted_Connection=True;MultipleActiveResultSets=true;"
    }
}

Program.cs:

builder.Services.Configure<ConnectionStrings>
              (builder.Configuration.GetSection("ConnectionStrings"));
builder.Services.AddSingleton<IDataService, DataService>();

ConnectionStrings.cs:

public class ConnectionStrings
{
    public string Database1 { get; set; }
}

DataService.cs:

public class DataService : IDataService
{
    private readonly ConnectionStrings _connectionStrings;

    public DataService(IOptions<ConnectionStrings> connectionStrings)
    {
        _connectionStrings = connectionStrings.Value;
    }
}

Page.razor:

@inject IDataService DataService 

...

_elements = await DataService.GetElementsByTerm(term);
...

Solution

  • A whole working demo you could follow:

    1.Be sure register DataService in Program.c

    builder.Services.Configure<ConnectionStrings>(
        builder.Configuration.GetSection("ConnectionStrings"));
    
    // Register DataService with dependency injection
    builder.Services.AddScoped<IDataService, DataService>();
    

    2.Implement the service

    public interface IDataService
    {
        string GetDatabaseName();
    }
    public class DataService : IDataService
    {
        private readonly ConnectionStrings _connectionStrings;
    
        public DataService(IOptions<ConnectionStrings> connectionStrings)
        {
            _connectionStrings = connectionStrings.Value;
        }
    
        public string GetDatabaseName()
        {
            var db = _connectionStrings.Database1;
            return db;
        }
    }
    

    3.Call service in Razor Component

    @page "/"
    @inject IDataService DataService
    
    <h3>Data Service Example</h3>
    @db
    
    @code {
        public string db { get; set; }
        protected override async Task OnInitializedAsync()
        {
            db = DataService.GetDatabaseName();
        }
    }