locked
Blazor - How to Read Connection Strings in appsettings.json RRS feed

  • Question

  • User135423268 posted

    Good Day Everyone

    I'm a beginner on using Blazor and currently experimenting things, so one of the things that I want to do is calling a ConnectionString from the appsettings.json.

    1st I create a Razor page then I created a partial class for that page, then I created a Class file which I put my function which connects to the SQL Server, Please take a note that I'm not using Entity Framework, what I'm using is Microsoft.Data.SqlClient.

    Here's my code on my partial class

    using BlazorTraining1.Models;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.Extensions.Configuration;
    using System.Data;
    using System.Net.Http;
    using BlazorTraining1.Services;
    using Microsoft.AspNetCore.Components;
    using Microsoft.Data.SqlClient;
    
    namespace BlazorTraining1.Pages
    {
        public partial class Test2
        {
    
            public List<EmployeeList> EL = new List<EmployeeList>();
            MyServivces GetMyServices = new MyServices();
            public string TestLang;
    
            
            
            protected override async Task OnInitializedAsync()
            {
    
    
                EL = GetMyServices.LoadEmployee("HR","True");
                await base.OnInitializedAsync();
            }
    
    
        }
    
    
    }
    

    and here's my class library

    using BlazorTraining1.Models;
    using Microsoft.AspNetCore.Hosting;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using MyClassLibrary_NetCore;
    using System.Data;
    using Microsoft.Data.SqlClient;
    using Microsoft.Extensions.Configuration;
    
    namespace BlazorTraining1.Services
    {
        public class MyServivces
        {
    
            private readonly IConfiguration _config;
    
            public MyServivces(IConfiguration iconfig)
            {
                this._config = iconfig;
            }
    
            
    
            public List<EmployeeList> LoadEmployee(string group,string active)
            {
                try
                {
                    string MyConn= _config.GetConnectionString("MyDB").ToString();
                    List<EmployeeList> GetEmployeeList = new List<EmployeeList>();
                   //I created a personal class library that I used on my projects and sorry I can't show the codes for this, but this class library shortens the amount of time of my coding when creating a SqlClient codes.
    
                    SQLCLCore GetSQLCL = new SQLCLCore(MyConn);
    
                    string[] getParam = new string[] { "@Group", "@Active" };
                    string[] getValues = new string[] { group, active };
    
                    DataTable dt = GetSQLCL.QueryDT("sp_GetEmployees", true, getParam, getValues);
    
                    foreach (DataRow GetRow in dt.Rows)
                    {
                        GetEmployeeList.Add(new EmployeeList()
                        {
                            EmployeeCode = GetRow["EmployeeCode"].ToString(),
                            FirstName = GetRow["FirstName"].ToString(),
                            MiddleName = GetRow["MiddleName"].ToString(),
                            FamilyName = GetRow["FamilyName"].ToString(),
                            Group = GetRow["Group"].ToString(),
                            Position = GetRow["Position"].ToString(),
                            Active = GetRow["Active"].ToString(),
                            Status = GetRow["Status"].ToString()
                        });
                    }
    
                    return GetEmployeeList;
                }
                catch(Exception ex)
                {
                    string exm = ex.Message;
                    return null;
                }
    
    
            }
    
        }
    }
    

    Here's my Connectionstring in appsettings.json

      "ConnectionStrings": {
        "MyDB": "Server=MyComputer\\SQLSVR16;Database=MyDatabase;Trusted_Connection=True;",
      }

    But when I'm running my project I'm got this error "CS7036 There is no argument given that corresponds to the required formal parameter 'iconfig' of 'MyServices.MyServices(IConfiguration)" I'm stuck here and I'm trying to fix this for hours but none of them seems to work, the other work around is type the connection string directly on a string variable in side the MyService class, which is working but, I prefer calling it on appsettings.json. Can someone help me on this? 

    Thanks everyone

    Friday, January 15, 2021 6:34 AM

Answers

  • User135423268 posted

    Good Day Everyone

    I have solved this by using this.

    What I did is I create a public string on the Startup.cs and then set the value on the Configure method.

       public class Startup
        {
            public static string MyConConn { get;private set; }
    
            public Startup(IConfiguration configuration)
            {
                Configuration = configuration;
            }
    
            public IConfiguration Configuration { get; }
    
    
    
            // This method gets called by the runtime. Use this method to add services to the container.
            // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
            public void ConfigureServices(IServiceCollection services)
            {
                services.AddRazorPages();
                services.AddServerSideBlazor();
                //services.AddSingleton<WeatherForecastService>();
    
    
                services.AddHttpClient<ITestService, TestServices>(client =>
                {
                    client.BaseAddress = new Uri("http://localhost:11197");
                });
            }
    
            // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
            public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
                else
                {
                    app.UseExceptionHandler("/Error");
                }
    
                app.UseStaticFiles();
    
                app.UseRouting();
    
                var builder = new ConfigurationBuilder();
    
                MyConn = Configuration.GetConnectionString("MyDB");
    
    
                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapBlazorHub();
                    endpoints.MapFallbackToPage("/_Host");
                });
            }
        }

    Then I call it on my Class file.

            public List<EmployeeList> LoadEmployee(string group,string active)
            {
    
                try
                {
    
    
                    string MyConnStr = Startup.MyConn;
                    List<EmployeeList> GetEmployeeList = new List<EmployeeList>();
    //I created a Class Library for SQL Transaction, I'm using Microsoft.Data.SQLClient SQLCLCore GetSQLCL = new SQLCLCore(MyConnStr); string[] getParam = new string[] { "@Group", "@Active" }; string[] getValues = new string[] { group, active }; DataTable dt = GetSQLCL.QueryDT("sp_LoadEmployees", true, getParam, getValues); foreach (DataRow GetRow in dt.Rows) { GetEmployeeList.Add(new EmployeeList() { EmployeeCode = GetRow["EmployeeCode"].ToString(), FirstName = GetRow["FirstName"].ToString(), MiddleName = GetRow["MiddleName"].ToString(), FamilyName = GetRow["FamilyName"].ToString(), Group = GetRow["Group"].ToString(), Position = GetRow["Position"].ToString(), Active = GetRow["Active"].ToString(), Status = GetRow["Status"].ToString() }); } return GetEmployeeList; } catch(Exception ex) { string exm = ex.Message; return null; } }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, January 26, 2021 3:18 AM

All replies

  • User-1545767719 posted

    amendoza29

    But when I'm running my project I'm got this error "CS7036 There is no argument given that corresponds to the required formal parameter 'iconfig' of 'MyServices.MyServices(IConfiguration)"

    Are you talking about the server side application such as ASP.NET Core MVC and Web API which supports the Blazor of client side from the server side?

    It seems to me that the DI does not work with your code for the initialization:

    MyServivces GetMyServices = new MyServices();

    Have you confirmed about it?

    Friday, January 15, 2021 9:08 AM
  • User-1545767719 posted

    I thought that the hosting model you use is the Blazor WebAssembly. But now I realized it seems the Blazor Server. (See Microsoft document "ASP.NET Core Blazor hosting models" if you need to know the difference)

    Please tell me if you choose the Blazor Server? I am afraid that you will change it to the Blazor WebAssembly after you study and know pros and cons between them.

    Saturday, January 16, 2021 1:07 AM
  • User-1545767719 posted

    I assume that the hosting model you use is the Blazor Server and that the DI does not work in your application.

    Try the followings:

    appsettings.json

    {
      "ConnectionStrings": {
        "NorthwindConnection": "Data Source=(local)\\sqlexpress;Initial Catalog=Northwind;Integrated Security=True"
      },
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft": "Warning",
          "Microsoft.Hosting.Lifetime": "Information"
        }
      },
      "AllowedHosts": "*"
    }

    MyService.cs 

    using System.Collections.Generic;
    using Microsoft.Extensions.Configuration;
    using System.Data.SqlClient;
    
    namespace SampleBlazorApp.Data
    {
        public class MyService
        {
            private readonly IConfiguration _configuration;
    
            public MyService(IConfiguration configuration)
            {
                this._configuration = configuration;
            }
    
            public List<Category> GetCategories()
            {
                string connString = _configuration.GetConnectionString("NorthwindConnection");
                string query = "SELECT [CategoryID], [CategoryName], [Description] FROM [Categories]";
                List<Category> categories = new List<Category>();
                using (SqlConnection connection = new SqlConnection(connString))
                {
                    using (SqlCommand command = new SqlCommand(query, connection))
                    {
                        connection.Open();
                        using (SqlDataReader reader = command.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                categories.Add(new Category
                                {
                                    CategoryID = reader.GetInt32(0),
                                    CategoryName = reader.GetString(1),
                                    Description = reader.GetString(2)
                                });
                            }
                        }
                    }
                }
                
                return categories;
            }
        }
    
        public class Category
        {
            public int CategoryID { set; get; }
            public string CategoryName { set; get; }
            public string Description { set; get; }
        }
    }

    Razor page (FetchMyService.razor)

    @page "/myservice"
    
    @using SampleBlazorApp.Data
    @inject MyService myService
    
    <h3>FetchMyService</h3>
    
    
    @if (categories == null)
    {
        <p><em>Loading...</em></p>
    }
    else
    {
        <table class="table">
            <thead>
                <tr>
                    <th>CategoryId</th>
                    <th>CategoryName</th>
                    <th>Description</th>
                </tr>
            </thead>
            <tbody>
                @foreach (var category in categories)
                {
                    <tr>
                        <td>@category.CategoryID</td>
                        <td>@category.CategoryName</td>
                        <td>@category.Description</td>
                    </tr>
                }
            </tbody>
        </table>
    }
    
    @code {
        private List<Category> categories;
    
        protected override void OnInitialized()
        {
            categories = myService.GetCategories();
        }
    }

    Startup.cs

    Add services.AddSingleton<MyService>(); to the existing code to enable DI as follows:

    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Hosting;
    using SampleBlazorApp.Data;
    
    namespace SampleBlazorApp
    {
        public class Startup
        {
            public Startup(IConfiguration configuration)
            {
                Configuration = configuration;
            }
    
            public IConfiguration Configuration { get; }
    
            public void ConfigureServices(IServiceCollection services)
            {
                services.AddRazorPages();
                services.AddServerSideBlazor();
                services.AddSingleton<WeatherForecastService>();
    
                services.AddSingleton<MyService>();  // Add this to enable DI
            }
    
            // other existing codes ... omitted
        }
    }

    I have confirmed that the above codes work as expected.

    Sunday, January 17, 2021 6:15 AM
  • User135423268 posted

    My apologise for the late response

    I'm using Server Side Application.

    Wednesday, January 20, 2021 7:21 AM
  • User135423268 posted

    Good Day Everyone

    I have solved this by using this.

    What I did is I create a public string on the Startup.cs and then set the value on the Configure method.

       public class Startup
        {
            public static string MyConConn { get;private set; }
    
            public Startup(IConfiguration configuration)
            {
                Configuration = configuration;
            }
    
            public IConfiguration Configuration { get; }
    
    
    
            // This method gets called by the runtime. Use this method to add services to the container.
            // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
            public void ConfigureServices(IServiceCollection services)
            {
                services.AddRazorPages();
                services.AddServerSideBlazor();
                //services.AddSingleton<WeatherForecastService>();
    
    
                services.AddHttpClient<ITestService, TestServices>(client =>
                {
                    client.BaseAddress = new Uri("http://localhost:11197");
                });
            }
    
            // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
            public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
                else
                {
                    app.UseExceptionHandler("/Error");
                }
    
                app.UseStaticFiles();
    
                app.UseRouting();
    
                var builder = new ConfigurationBuilder();
    
                MyConn = Configuration.GetConnectionString("MyDB");
    
    
                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapBlazorHub();
                    endpoints.MapFallbackToPage("/_Host");
                });
            }
        }

    Then I call it on my Class file.

            public List<EmployeeList> LoadEmployee(string group,string active)
            {
    
                try
                {
    
    
                    string MyConnStr = Startup.MyConn;
                    List<EmployeeList> GetEmployeeList = new List<EmployeeList>();
    //I created a Class Library for SQL Transaction, I'm using Microsoft.Data.SQLClient SQLCLCore GetSQLCL = new SQLCLCore(MyConnStr); string[] getParam = new string[] { "@Group", "@Active" }; string[] getValues = new string[] { group, active }; DataTable dt = GetSQLCL.QueryDT("sp_LoadEmployees", true, getParam, getValues); foreach (DataRow GetRow in dt.Rows) { GetEmployeeList.Add(new EmployeeList() { EmployeeCode = GetRow["EmployeeCode"].ToString(), FirstName = GetRow["FirstName"].ToString(), MiddleName = GetRow["MiddleName"].ToString(), FamilyName = GetRow["FamilyName"].ToString(), Group = GetRow["Group"].ToString(), Position = GetRow["Position"].ToString(), Active = GetRow["Active"].ToString(), Status = GetRow["Status"].ToString() }); } return GetEmployeeList; } catch(Exception ex) { string exm = ex.Message; return null; } }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, January 26, 2021 3:18 AM