简体   繁体   中英

How to use proper connection string .net core console application

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:

  1. Database Project (ENTITY FRAMEWORK CORE)
  2. Console App ( REFERENCING TO DATABASE PROJECT)
  3. 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

One option I can suggest is to create another DBContextClass in your console application and just override the OnConfiguring method to read from appsettings of console application project

Example: New Class in Console Application

public class ConsoleProductXmlDBContext : ProductXmlDBContext
    {
        private readonly IConfiguration _iConfiguration;
        private readonly string _connectionString;

        public ConsoleProductXmlDBContext()
        {
            IConfigurationBuilder builder = new ConfigurationBuilder()
                        .SetBasePath(Directory.GetCurrentDirectory())
                        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
            _iConfiguration = builder.Build();
            _connectionString = _iConfiguration.GetConnectionString("DefaultConnection");
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            _ = optionsBuilder.UseSqlServer(_connectionString, providerOptions => providerOptions.CommandTimeout(60))
                          .UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
        }
    }

Usage in Console Application

using (var context = new ConsoleProductXmlDBContext())
{
    companies = context.Companies.ToList();
}

Check the documentation here: https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.dbcontext.onconfiguring?view=efcore-5.0

In situations where an instance of DbContextOptions may or may not have been passed to the constructor, you can use IsConfigured to determine if the options have already been set, and skip some or all of the logic in OnConfiguring(DbContextOptionsBuilder).

So you can check the IsConfigured value and do nothing if options have been provided already.

The proper solution though, would be to have the overridden function read from the configuration directly, if there is no reason to override it at the first place.

https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/?view=aspnetcore-5.0#publish-to-a-folder The published folder will contain the proper configuration file, depending on which application you published.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM