当前项目(三层体系结构)是基于类库项目-实体框架,上下文类和其中的所有实体的存储层-一直由mvc项目使用,所有时间都很好(所有.net框架),
在将dotnet核心控制台应用程序设置为目标.netframework之后,成功地添加并添加了dotnet核心控制台应用程序以成功将其用作存储库类库项目的自动化作业。
到目前为止,一切正常,直到这段代码为止
在类库项目app.config中设置配置,未加载, dotnetcore控制台应用程序已经在json文件中拥有了自己的配置,并且一切正常 DBcontext类
public class DBContext : IdentityDbContext<User> //ApplicationUser
{
public DBContext()
: base("DatabaseConnectionString", throwIfV1Schema: false)
{
// here just checking and found out all configs are missing
var cnns = ConfigurationManager.ConnectionStrings[0];
Configuration.LazyLoadingEnabled = false;
Database.CommandTimeout = 900;
}
dotnet核心控制台应用程序入口类
class Program
{
private static IConfigurationRoot ConfigurationRoot { get; set; }
private static IServiceProvider ServiceProvider { get; set; }
private static readonly string env;
static Program()
{
env = Environment.GetEnvironmentVariable("env");
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env}.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables();
ConfigurationRoot = builder.Build();
}
static void Main(string[] args)
{
var mySettingsConfig = new GeneralConfiguration();
ConfigurationRoot.GetSection("GeneralConfiguration").Bind(mySettingsConfig);
//it's here
string DatabaseConnectionString = ConfigurationRoot.GetConnectionString("DatabaseConnectionString");
Console.WriteLine($"Welcome to {mySettingsConfig.AppName} , {Environment.NewLine}Please note that You are running an {env} configured Application");
var serviceCollection = new ServiceCollection()
.RegisterServices();
serviceCollection.AddOptions();
serviceCollection.Configure<GeneralConfiguration>(ConfigurationRoot.GetSection(nameof(GeneralConfiguration)));
ServiceProvider = serviceCollection.BuildServiceProvider();
var syncService = ServiceProvider.GetService<ISyncService>();
syncService.SyncTheStuff();
}
}
有两种解决方法和一种可能的解决方案 1-只是重构上下文类似乎是最佳解决方案,但是它将包括大量重构,
2-或在构造函数中添加一些if语句,以便如果dotnet核心控制台应用程序使用的类库是从备用位置(xml,json文件)加载缺少的配置,
3-best解决方案使类库项目从dotnet核心控制台应用程序加载配置