Harish Batchu

Harish Batchu

  • NA
  • 255
  • 70.9k

How can i access connection string form appsetting.json file

Jun 24 2019 12:58 AM
I have connection string in appsettings.json file. I need to access that connection string Class library Project. i done the following code to access connection stirng but still i am getting null.
 
startup.cs
  1. public Startup(IConfiguration configuration)  
  2. {  
  3. Configuration = configuration;  
  4. }  
  5. public IConfiguration Configuration { get; }  
  6. // This method gets called by the runtime. Use this method to add services to the container.  
  7. public void ConfigureServices(IServiceCollection services)  
  8. {  
  9. services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);  
  10. services.AddSingleton<IConfiguration>(Configuration);  
  11. }  
In class library project
  1. protected string ConnectionString;  
  2. protected int CommandTimeout;  
  3. private IConfiguration _config;  
  4. #endregion  
  5. public Database(IConfiguration configuration)  
  6. {  
  7. _config = configuration;  
  8. }  
  9. #region Constructor  
  10. public Database()  
  11. {  
  12. ConnectionString = _config.GetConnectionString("DefaultConnection");  
  13. CommandTimeout = 60;  
  14. }  
Please give me solution for this ASAP
 
and i gone through the below link
 
https://stackoverflow.com/questions/51304432/how-to-read-connection-string-inside-net-standard-class-library-project-from-as
 
but i could not understand to inject the connection stings

Answers (6)