gpt4 book ai didi

c# - .Net Core 3 控制台无法从 appsettings 获取连接字符串

转载 作者:行者123 更新时间:2023-12-05 01:34:06 24 4
gpt4 key购买 nike

我已经创建了一个 .Net Core 3.1 控制台应用程序,并且正在尝试使用 EntityFramework 来处理我的 Oracle 数据库。我发现了一些关于这个主题的视频和文章,但它们都涉及 HTTP 应用程序而不是控制台应用程序。

我使用 powershell 命令构建表并创建一个名为 ModelContextDbContext。在我的 Program.cs 中,我有一个 Host.CreateDefaultBuilder 并添加了 services.AddDbContext 并将连接字符串放入我的 appsettings.json 文件中。

我的问题是,当它试图将上下文添加到主机中的服务时,我无法让它从应用程序设置中提取连接字符串。我在 Configuration.GetConnectionString 上收到设计时错误,提示 “Configuration does not contain a definition for ‘GetConnectionString’”

我通过 NuGet 安装了 System.Configuration.ConfigurationManager 并在我的 Program.cs 文件中添加了 using System.Configuration。如何从我的主机构建器中的应用程序设置中获取连接字符串?

程序.cs

var host = Host.CreateDefaultBuilder().ConfigureServices((context, services) =>
{
services.AddTransient<IAppHost, AppHost>();
services.AddTransient<IFileManager, FileManager>();
services.AddTransient<IDataManager, DataManager>();

var connstring = Configuration.GetConnectionString("DbConnection");
services.AddDbContext<ModelContext>(options =>
{
options.UseOracle(connstring);
});

services.AddLogging(builder =>
{
builder.AddNLog("nlog.config");
});
}).Build();

更新代码

这是我的 Program.cs 文件中的所有代码。不幸的是,我不确定我做了什么导致这种情况,但现在我的 FileManger 类出现错误。

Unable to resolve service for type 'Microsoft.Extensions.Logging.Logger`1[EmailUpdateExport.FileManager]' while attempting to activate 'EmailUpdateExport.FileManager'.

我什至取消了从我刚刚添加的应用程序设置中获取 DbConnection 的代码,但仍然出现错误。

class Program
{
static void Main(string[] args)
{
//Calls the Builder so that you can get to the appsettings.
var builder = new ConfigurationBuilder();
BuildConfig(builder);

var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();

try
{
logger.Debug("Initializing Program.Main");

var host = Host.CreateDefaultBuilder()
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.SetBasePath(Path.Combine(AppContext.BaseDirectory));
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
})
.ConfigureServices((context, services) =>
{
services.AddTransient<IAppHost, AppHost>();
services.AddTransient<IFileManager, FileManager>();
services.AddTransient<IDataManager, DataManager>();

var connstring = context.Configuration["ConnectionStrings:DbConnection"];
services.AddDbContext<ModelContext>(options =>
{
options.UseOracle(connstring);
});

services.AddLogging(builder =>
{
builder.AddNLog("nlog.config");
});
}).Build();


//Create instance of AppHost and call the Run() function to run the business logic.
var svc = ActivatorUtilities.CreateInstance<AppHost>(host.Services);
svc.Run();
}
catch (Exception ex)
{
//NLog: catch setup errors
logger.Error("Stopped program setup with Error. {0} | {1} | {2}", ex.Message, ex.StackTrace, ex.InnerException);
throw;
}
finally
{
// Ensure to flush and stop internal timers/threads before application-exit
NLog.LogManager.Shutdown();
}
}

static void BuildConfig(IConfigurationBuilder builder)
{
//Sets up the ability to talk to the appsettings.json
builder.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)
.AddEnvironmentVariables();
}

}

这是我的 FileManger,以防有人对此提出建议。

public class FileManager : IFileManager
{
private readonly ILogger<FileManager> _log;
private readonly IConfiguration _configuration;

public FileManager(Logger<FileManager> log, IConfiguration config)
{
_log = log;
_configuration = config;
}

public void CreateFileDirectory(string FilePath)
{
try
{
//create the target location if it doesn't exist
if (!Directory.Exists(FilePath))
{
_log.LogInformation("Create directory: " + FilePath);
Directory.CreateDirectory(FilePath);
}
}
catch (Exception ex)
{
_log.LogError("Error creating Export directory. {0} | {1} | {2} ", ex.Message, ex.StackTrace, ex.InnerException);
}
}


public void CopyFile(string sourceLocation, string destinationLocation, string fileName)
{
_log.LogInformation("Source location: {0} | Destination location: {1} | File Name: {2}", sourceLocation, destinationLocation, fileName);

var sourceFile = Path.Combine(sourceLocation, fileName);
var destinationFile = Path.Combine(destinationLocation, fileName);

_log.LogInformation("SourceFilePath: {0}", sourceFile);
_log.LogInformation("DestinationFilePath: {0}", destinationFile);

try
{
//check to make sure source exists first
if (File.Exists(sourceFile))
{
//get rid of the file if it already exists. Shouldn't be an issue most to the time.
if (File.Exists(destinationFile))
{
File.Delete(destinationFile);
}
File.Copy(sourceFile, destinationFile);
}
else
_log.LogInformation("Source file does not exist. File: {0}", sourceFile);

}
catch (Exception ex)
{
_log.LogError("Error copying file. Source: {0} | Destination: {1}. {2} | {3} | {4}", sourceFile, destinationFile, ex.Message, ex.StackTrace, ex.InnerException);
throw;
}

}

最佳答案

这是您可以做到的一种方式。此示例根据键名访问配置值。将此配置映射到一个类是个好主意,这样检索设置就不容易出错。您可以查看我在评论中发布的链接,了解有关如何操作的详细信息。

var host = Host.CreateDefaultBuilder()
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.SetBasePath(Path.Combine(AppContext.BaseDirectory));
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
})
.ConfigureServices((hostContext, services) =>
{
services.AddDbContext<ModelContext>(options =>
{
options.UseSqlServer(hostContext.Configuration["ConnectionStrings:DefaultConnection"]);
}, ServiceLifetime.Transient)
// add other services
})
.UseConsoleLifetime()
.Build();

应用设置.json:

{
"ConnectionStrings": {
"DefaultConnection": "Server=localhost;Database=myDB;Trusted_Connection=True;"
},
.....
}

关于c# - .Net Core 3 控制台无法从 appsettings 获取连接字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64029917/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com