簡體   English   中英

使用IServiceCollection.AddSingleton()的單個對象實例

[英]Single object instance using IServiceCollection.AddSingleton()

考慮以下簡單的appsettings.json:

{
  "maintenanceMode": true
}

它被加載到我的Startup.cs / Configure(...)方法中

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{

    // Load appsettings.json config
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
    _configuration = builder.Build();

    // Apply static dev / production features
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseHsts();
    }

    // Other features / settings
    app.UseHttpsRedirection();
    app.UseMvc();
}

_configuration在Startup.cs中是私有的,用於將內容反序列化為結構化模型,該模型將在整個Web服務生存期內提供附加功能

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services) {
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

    services.AddOptions();

    var runtimeServices = _configuration.Get<RuntimeServices>();

    services.AddSingleton(runtimeServices);
}

該模型如下所示:

public class RuntimeServices {

    [JsonProperty(PropertyName = "maintenanceMode")]
    public bool MaintenanceMode { get; set; }

}

控制器如下所示:

[ApiController]
public class ApplicationController : Base.Controller {

    private readonly RuntimeServices _services;

    public ApplicationController(IOptions<RuntimeServices> services) : base(services) {
        _services = services.Value;
    }

    // Web-api following ...

}

現在問題來了:

在啟動並加載了appsettings.json並反序列化之后,RuntimeServices實例會在啟動后立即保存所有正確的信息(是的,此處省略了其中的一些信息)。

Startup.cs / ConfigureServices()中的哈希碼: 在此處輸入圖片說明

任何控制器/ api調用內的哈希碼: 在此處輸入圖片說明

GetHashCode()方法尚未被篡改。 這導致未在控制器/ api調用中應用源自表單appsettings.json的配置,所有屬性均使用其默認值/ null實例化。

我希望使用AddSingleton()方法將注入相同的實例,並在應用程序的整個生命周期內重復使用它。 有人可以告訴我為什么要創建RuntimeServices的新實例嗎? 我該如何歸檔我的目標,即在Startup.cs中擁有我的對象的可用實例 ,並仍然在控制器中訪問相同的對象實例

我的首選解決方案將是通常的單例模式。 但是我希望使用asp.net核心提供的內置功能來解決此問題。

因為此調用:

services.AddSingleton(runtimeServices);

注冊RuntimeServices的實例,它不配置IOptions<RuntimeServices> 因此,當您請求IOptions<RuntimeServices> ,沒有任何選項,並且您將獲得一個具有所有默認值的新實例。

您想要:

  1. 保留AddSingleton並使用public ApplicationController(RuntimeServices services)

  2. 刪除AddSingleton調用並使用services.Configure<RuntimeServices>(_configuration)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM