gpt4 book ai didi

dependency-injection - 使用 RavenDB 设置 dotnet 核心

转载 作者:行者123 更新时间:2023-12-05 00:16:00 25 4
gpt4 key购买 nike

我目前在为多个环境设置带有 dotnet 核心的 RavenDB 时遇到问题。

在 StartUp 类中,我将 Raven 配置为 Singleton 并使用 IOptions 模式将设置 Raven 绑定(bind)到 RavenSettings 对象。

 public virtual void ConfigureServices(IServiceCollection services)
{
Services.AddMvc()

//Add functionality to inject IOptions<T>
services.AddOptions();

// App Settings
services.Configure<RavenSettings>(Configuration.GetSection("Raven"));
//services.Configure<RavenSettings>(settings => Configuration.GetSection("Raven").Bind(settings));

// .NET core built in IOC
services.AddSingleton(DocumentStoreHolder.Store);
services.AddSingleton<IConfiguration>(Configuration);
}

这是我的默认应用设置。
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
},
"Raven": {
"Url": "x",
"DefaultDatabase": "x"
}
}

这是我尝试将设置从 appsettings 绑定(bind)到...的类
public class RavenSettings
{
public string Url { get; set; }
public string DefaultDatabase { get; set; }
}

下面的类在生成 Raven 文档存储时遵循 Raven 文档。因为我使用的是单例,所以我没有点击构造函数来注入(inject)设置。任何人都可以建议解决这个问题吗?
public sealed class DocumentStoreHolder
{
private static RavenSettings _ravenSettings;

public DocumentStoreHolder(IOptions<RavenSettings> ravenSettings)
{
_ravenSettings = ravenSettings.Value;
}

public static IDocumentStore Store => DocStore.Value;

private static readonly Lazy<IDocumentStore> DocStore = new Lazy<IDocumentStore>(CreateStore);

private static IDocumentStore CreateStore()
{
var store = new DocumentStore
{
Url = _ravenSettings.Url,
DefaultDatabase = _ravenSettings.DefaultDatabase
}.Initialize();

return store;
}
}

最佳答案

基于 Set 的回答,我能够通过创建 IDocumentStoreHolder 接口(interface)并在 IOC 中注册它来解决它。

DocumentStoreHolder.cs

public class DocumentStoreHolder : IDocumentStoreHolder
{
public DocumentStoreHolder(IOptions<RavenSettings> ravenSettings)
{
var settings = ravenSettings.Value;

Store = new DocumentStore
{
Url = settings.Url,
DefaultDatabase = settings.DefaultDatabase
}.Initialize();
}

public IDocumentStore Store { get; }
}

IDocumentStoreHolder.cs
public interface IDocumentStoreHolder
{
IDocumentStore Store { get; }
}

Startup.cs(配置服务)
services.AddSingleton<IDocumentStoreHolder, DocumentStoreHolder>();

SomeClass.cs
private readonly IDocumentStore _store;

public SomeClass(IDocumentStoreHolder documentStoreHolder)
{
_store = documentStoreHolder.Store;
}

关于dependency-injection - 使用 RavenDB 设置 dotnet 核心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43115547/

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