How to read connection string inside .NET Standard Class library project from ASP.NET Core

Forums .NET CoreHow to read connection string inside .NET Standard Class library project from ASP.NET Core
Staff asked 2 years ago

Using this code you can get the connection string from ‘appsettings.json‘ file.

private IConfiguration _config;

public DataAccess(IConfiguration config)
{
    _config = config;
}

public void Method()
{
   var connectionStr = _config.GetValue<string>("App:Connection:Value"); 
}

 

Parth Mandaliya replied 2 years ago

Answers (1)

Add Answer
Staff answered 2 years ago

Let’s assume in your .net core app, you have a configuration file that looks something like this:

{
  "App": {
    "Connection": {
      "Value": "connectionstring"
    }
  }
}

In your data access layer (class library) you can take a dependency on IConfiguration

public class DataAccess : IDataAccess
{
    private IConfiguration _config;

    public DataAccess(IConfiguration config)
    {
        _config = config;
    }

    public void Method()
    {
        var connectionString = _config.GetValue<string>("App:Connection:Value"); //notice the structure of this string
        //do whatever with connection string
    }
}

Now, in your ASP.net Core web project, you need to ‘wire up’ your dependency. In Startup.cs, I’m using this (from the default boilerplate template)

public class Startup
{
    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.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
        services.AddSingleton<IConfiguration>(Configuration); //add Configuration to our services collection
        services.AddTransient<IDataAccess, DataAccess>(); // register our IDataAccess class (from class library)
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseMvc();
    }
}

Now, when your code in your class library gets executed, the ctor gets handed the instance of IConfiguration you have set up in your web app

Subscribe

Select Categories