I have scenario where I have to expand my project with .NET CORE WEB API PROJECT.
In the beginning it was just console app which was working as a windows service on a simple tasks, adding data from xml files to database.
And my structure looks like this:
- Database Project (ENTITY FRAMEWORK CORE)
- Console App ( REFERENCING TO DATABASE PROJECT)
- Web Api (REFERENCING TO DATABASE PROJECT)
Now when I created WEB API project it requires me to register Context in Startup.cs and I did it like this:
Startup.cs
// DbContext for MSSQL
services.AddDbContextPool<ProductXmlDBContext>(options => options.UseSqlServer(_configuration.GetConnectionString(Config.CONNECTION_STRING)));
And that is all fine.
But now I want to read connection string for console application for it's own connection string (appsettings.json) since when I created API it got his own appsettings.json where I'm storing connection string for WEB API.
My DBContext looks like this:
public ProductXmlDBContext()
{
}
// I added this because it was required for WEB API to work
public ProductXmlDBContext(DbContextOptions<ProductXmlDBContext> options) : base(options)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(@"Server=localhost;Database=ProductXml;Trusted_Connection=True;");
}
In my console app I have add appsettings.json
And here is my Program.cs:
static void Main(string[] args)
{
try
{
// Set up configuration sources.
var builder = new ConfigurationBuilder()
.SetBasePath(Path.Combine(AppContext.BaseDirectory))
.AddJsonFile("appsettings.json", optional: true);
var services = new ServiceCollection();
Configuration = builder.Build();
//
var x = Configuration.GetConnectionString("DefaultConnection");
services.AddDbContextPool<ProductXmlDBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
}
}
And here is how I use Context in my console application:
using (var context = new ProductXmlDBContext())
{
companies = context.Companies.ToList();
}
And probably because of this usage it uses value from protected override void OnConfiguring method instead from its own appsettings.json ?
So how could I read connection string for this console application only from itself appsettings.json
(to remove/avoid using hardcoded value) from context.
Edit:
There is no GetConnectionString option:
Thanks a lot!
Cheers

