[英]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.我有一个场景,我必须使用 .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.一开始它只是一个控制台应用程序,它作为 windows 服务在一个简单的任务上工作,将 xml 文件中的数据添加到数据库中。
And my structure looks like this:我的结构如下所示:
Now when I created WEB API project it requires me to register Context in Startup.cs and I did it like this:现在,当我创建 WEB API 项目时,它要求我在 Startup.cs 中注册 Context,我是这样做的:
Startup.cs启动.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. 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:我的 DBContext 看起来像这样:
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
在我的控制台应用程序中,我添加
appsettings.json
And here is my Program.cs
:这是我的
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:以下是我在控制台应用程序中使用 Context 的方式:
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
?并且可能由于这种用法,它使用来自
protected override void OnConfiguring
方法的值,而不是来自它自己的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.那么我如何才能从上下文中
appsettings.json
(以删除/避免使用硬编码值)读取此控制台应用程序的连接字符串。
Edit:编辑:
There is no GetConnectionString
option:没有
GetConnectionString
选项:
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我可以建议的一个选项是在您的控制台应用程序中创建另一个 DBContextClass 并覆盖 OnConfiguring 方法以从控制台应用程序项目的 appsettings 中读取
Example: New Class in Console Application示例:控制台应用程序中的新 Class
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在此处查看文档: 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).
在 DbContextOptions 的实例可能已传递或未传递给构造函数的情况下,您可以使用 IsConfigured 来确定选项是否已设置,并跳过 OnConfiguring(DbContextOptionsBuilder) 中的部分或全部逻辑。
So you can check the IsConfigured
value and do nothing if options have been provided already.因此,您可以检查
IsConfigured
值,如果已提供选项,则不执行任何操作。
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.但是,正确的解决方案是让被覆盖的 function 直接从配置中读取,如果没有理由首先覆盖它。
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. https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/?view=aspnetcore-5.0#publish-to-a-folder发布的文件夹将包含正确的配置文件,具体取决于您发布了哪个应用程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.