ASP.NET Core:从解决方案中的另一个项目访问应用程序设置 [英] ASP.NET Core: Accessing appsettings from another project in solution
问题描述
在我的Startup.cs
类中,我具有以下配置构建,用于初始化数据库上下文:
In my Startup.cs
class I have the following config build which initializes the db context:
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", true, true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json",true)
.AddEnvironmentVariables();
Configuration = builder.Build();
NHibernateUnitOfWork.Init(Configuration["ConnectionStrings:OracleConnection"]);
NHibernateUnitOfWork
与类库项目位于不同的项目中.我希望能够注入(或以某种方式通过设置),而不是在我的Startup.cs
类中使用NHibernateUnitOfWork.Init
.
NHibernateUnitOfWork
is located in a different project as a class library project. I want to be able to inject (or somehow pass the settings) instead of using the NHibernateUnitOfWork.Init
in my Startup.cs
class.
我可以在我的类库中构建appsettings,但尝试避免这种情况.
I can build the appsettings in my class library but trying to avoid that.
执行此操作的明智方法是什么?
What is a sane way to do this ?
推荐答案
您可以注入它.
在您的Startup.cs
类中,您可以将以下内容添加到您的ConfigureServices(IServiceCollection services)
方法中:
In your Startup.cs
class, you can add the following to your ConfigureServices(IServiceCollection services)
method:
services.AddSingleton(Configuration);
从那里,您可以使用构造函数注入,并像往常一样在下游使用它:
From there, you can use constructor injection and consume it downstream the same way you normally would:
public class SomeClass
{
public SomeClass(IConfigurationRoot configuration)
{
NHibernateUnitOfWork.Init(Configuration["ConnectionStrings:OracleConnection"]);
}
}
注意:这假定Configuration
是在您的Startup.cs
类中定义的:
NOTE: This assumes Configuration
is defined in your Startup.cs
class:
public static IConfigurationRoot Configuration;
这篇关于ASP.NET Core:从解决方案中的另一个项目访问应用程序设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!