c# - ASP.NET 核心 : Accessing appsettings from another project in solution

标签 c# asp.net asp.net-core

在我的 Startup.cs 类中,我有以下初始化数据库上下文的配置构建:

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 类中注入(inject)(或以某种方式传递设置)而不是使用 NHibernateUnitOfWork.Init

我可以在我的类库中构建应用程序设置,但尽量避免这种情况。

执行此操作的明智方法是什么?

最佳答案

你可以注入(inject)它。

在您的 Startup.cs 类中,您可以将以下内容添加到您的 ConfigureServices(IServiceCollection services) 方法中:

services.AddSingleton(Configuration);

从那里,您可以使用构造函数注入(inject)并像往常一样在下游使用它:

public class SomeClass
{
    public SomeClass(IConfigurationRoot configuration) 
    {
        NHibernateUnitOfWork.Init(Configuration["ConnectionStrings:OracleConnection"]);
    }
}

注意:这假设 Configuration 是在您的 Startup.cs 类中定义的:

public static IConfigurationRoot Configuration;

关于c# - ASP.NET 核心 : Accessing appsettings from another project in solution,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37568084/

相关文章:

c# - 将SignalR的ITransportHeartbeat添加到Autofac

asp.net - 适用于移动应用程序和 Web 管理面板的 Azure 移动应用服务或 Web 应用服务

c# - Unity 生成的对象不会向前旋转

c# - 如何从 C# 中的列表框和对象列表中删除项目

c# - 在 Telerik MVC AJAX 绑定(bind)属性列上使用自定义日期格式化程序

.net - 你如何在 .NET Core 中获得 post 值

c# - asp .net core 中的自动 Controller 检测

c# - SaveChanges() 方法不保存对数据库的更改

c# - 在 C# 中计算数组频率分布的最快方法是什么?

ASP.NET MVC 表单和双字段