How to read connection string inside .NET Standard Class library project from ASP.NET Core
You can inject an instance of a class that implements IConfiguration
See Here
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
Note:
You can create strongly typed settings class if you'd prefer, see here for more information
How do I get a connection string in a .net core standard class library from the configuration file in a .net core 2.0 web app?
It is very much possible to access "connection strings" or other configuration data easily in .Net core without much additional effort.
Just that the configuration system has evolved (into something much better) & we have to make allowances for this as well (& follow recommended practices).
In your case as you are accessing the connection string value in a standard library (intended to be reused), you should not make assumptions as how the configuration values will be "fed" to your class. What this means is you should not write code to read a connection string directly from a config file - instead rely on the dependency injection mechanism to provide you with the required configuration - regardless of how it has been made available to your app.
One way to do this is to "require" an IConfiguration object to be injected into your class constructor & then use the GetValue method to retrieve the value for the appropriate key, like so:
public class IndexModel : PageModel
{
public IndexModel(IConfiguration config)
{
_config = config;
}
public int NumberConfig { get; private set; }
public void OnGet()
{
NumberConfig = _config.GetValue<int>("NumberKey", 99);
}
}
In .net core, before the app is configured and started, a "host" is configured and launched. The host is responsible for app startup and lifetime management. Both the app and the host are configured using various "configuration providers". Host configuration key-value pairs become part of the app's global configuration.
Configuration sources are read in the order that their configuration providers are specified at startup.
.Net core supports various "providers". Read this article for complete information on this topic.
Reading connection string placed in ASP.NET Core from class library. Database First
You can take the advantage of .Net Core Dependency Injection and out of box features. Your connection string will remain in web project but you can use DB context without declaring any connection string in Class Library Project. I am sharing code sample from my existing project.
Set Connection String
You have referenced connection string in your start up and added to services. You don't need to define the connection string again and use the db context using Built in DI. The code could look like this !
Start up class
Set up your SQL config. Look closely at MigrationsAssembly this is where you would reference your class library project.
public static IServiceCollection AddCustomDbContext(this IServiceCollection services, IConfiguration configuration)
{
// Add DbContext using SQL Server Provider
services.AddDbContext<PaymentDbContext>(options =>
options.UseSqlServer(configuration.GetConnectionString("myconnectionstring"), x => x.MigrationsAssembly("Payment.Persistence")));
return services;
}
Context Class
This class is in your class library project.
public class PaymentDbContext : DbContext
{
public PaymentDbContext(DbContextOptions<PaymentDbContext> options)
: base(options)
{
}
public DbSet<Payments> Payments { get; set; }
}
Use DI to access Context
private readonly PaymentDbContext _context;
public PaymentsRepository(PaymentDbContext dbContext)
{
_context = dbContext;
}
EF Core Reading Connection String From User Secret Using Class Library Project and DB Scaffolding
It works for me in ASP.NET Core 6 and EfCore v6.0.1
.
Here the steps I've done:
- Create ASP.NET Core Web API and class lib projects
-- > WebApp.Api\
|
> WebApp.Data\
|
> WebApp.sln
- Set connection string secret for
WebApp.Api
. Ensure thatUserSecretsId
is added to csprojPropertyGroup
:
> dotnet user-secrets init
> dotnet user-secrets set "ConnectionStrings:MyConnString" "<conn-string>"
- Install
Microsoft.EntityFrameworkCore
andMicrosoft.EntityFrameworkCore.SqlServer
intoWebApp.Data
. Add project reference fromWebApp.Api
toWebApp.Data
. - Install
Microsoft.EntityFrameworkCore.Design
nuget forWebApp.Api
project. - In cmd navigate to
WebApp.Api
project folder and run the following command:
> dotnet ef dbcontext scaffold Name=ConnectionStrings:MyConnString "Microsoft.EntityFrameworkCore.SqlServer" -p ..\WepApp.Data\
In that case for the scaffold
command startup project is WebApp.Api
and target project is WebApp.Data
ASP.NET Core 3.1 get connection string in class library
Your are mapping your configuration to ConnectionString object located on your main Web app(which you called WWW project). You have a dependency from Web project to DAL class library as expected. you can not call the classes in Main app from DAL project. You may locate your ConnectionString at DAL project or some another layer which both projects have dependency towards. Also, you can directly call Configuration.GetSection(..)... when Configuration is the injected instance of IConfiguration.
Related Topics
Localization of Displaynameattribute
Bring a Window to the Front in Wpf
C# Store Functions in a Dictionary
Right Click Context Menu for Datagridview
Getting the Application's Directory from a Wpf Application
Concat All Strings Inside a List<String> Using Linq
How to Get This ASP.NET MVC Selectlist to Work
Convert Any Object to a Byte[]
An Object Reference Is Required to Access Non-Static Member
Windows Application Startup Error Exception Code: 0Xe0434352
Why Does "Abcd".Startswith("") Return True
Howto Implement Callback Interface from Unmanaged Dll to .Net App
How to Sort Strings Alphabetically While Accounting for Value When a String Is Numeric