我创建了一个.Net Core 3.1控制台应用程序,尝试使用EntityFramework来操作我的Oracle数据库。我找到了一些视频和文章,但它们都是处理HTTP应用程序而不是控制台应用程序。
我使用PowerShell命令生成表并创建了一个名为 ModelContext
的DbContext
。在我的Program.cs中,我使用Host.CreateDefaultBuilder
添加services.AddDbContext
,并将连接字符串放入appsettings.json文件中。
我的问题是,在尝试将上下文添加到主机中的服务时,无法从appsettings中获取连接字符串。在Configuration.GetConnectionString处出现设计时错误,显示“Configuration不包含‘GetConnectionString’的定义”。
我通过NuGet安装了System.Configuration.ConfigurationManager
并在我的Program.cs文件中添加了using System.Configuration
。
如何从主机构建器中获取appsettings中的连接字符串?
Program.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文件中所有的代码。不幸的是,我不确定我做了什么导致了这个问题,现在我的FileManager类出现了错误。
Unable to resolve service for type 'Microsoft.Extensions.Logging.Logger`1[EmailUpdateExport.FileManager]' while attempting to activate 'EmailUpdateExport.FileManager'.
我已经撤销了从刚刚添加的appsettings中获取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();
}
}
这是我的文件管理器,如果有建议,请提出来。
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;
}
}