簡體   English   中英

ASP.NET Core 2.1 - 選項模式 - 訪問選項不返回綁定類的實例

[英]ASP.NET Core 2.1 - Options pattern - accessing options doesn't return instance of the bound class

我正在嘗試按照Microsoft Docs 中的這個示例從我的 ASP.NET Core 2.1 應用程序中的 appsettings.json 文件中檢索一些配置選項。

我已經綁定了班級

public class MailServer
{
    public string Host { get; set; }
    public int Port { get; set; }
    public bool UseSSL { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
    public string FromAddress { get; set; }
    public MailServer()
    {
    }
}

到 Startup.cs 中的配置

public void ConfigureServices(IServiceCollection services)
{
    // .....
    services.Configure<MailServer>(Configuration.GetSection("MailServer"));
    // .....
    services.AddSingleton<IScheduledTask, ScheduledTask>();
}

在啟動時,我還添加了 ScheduledTask 作為單例,以便從該特定類訪問上下文 - 這也是我想要訪問選項的地方。

public interface IScheduledTask
{
    void MonitorCloudHosts();
}

public class ScheduledTask : IScheduledTask
{
    private readonly IServiceProvider _ServiceProvider;
    private readonly MailServer _mailServer;

    // note here you ask to the injector for IServiceProvider
    public ScheduledTask(IServiceProvider serviceProvider, IOptions<MailServer> optionsAccessor)
    {
        _ServiceProvider = serviceProvider;
        _mailServer = optionsAccessor.Value;
    }

    public void MonitorCloudHosts()
    {
        // Do some stuff
        var xyz = _mailServer.Host;
    }
}

這是我的 appsettings.json 文件:

  {
    "Logging": {
      "LogLevel": {
        "Default": "Warning"
      }
    },
    "AllowedHosts": "*",
    "ConnectionStrings": {
      "CloudMonitorConnection": "Server=.\\SQLEXPRESS;Database=CloudMonitor;Integrated Security=SSPI;MultipleActiveResultSets=true;",
      "HangFireConnection": "Server=.\\SQLEXPRESS;Database=HangFire;Integrated Security=SSPI;"
    },
    "MailServer": {
      "Host": "smtp.gmail.com",
      "Port": "587",
      "UseSSL": "True",
      "Username": "xxxxxxx@gmail.com",
      "Password": "xxxxxxx",
      "FromAddress": "xxxxxxx<xxxxxxx@gmail.com>"
    }
  }

編譯器在調用 _mailServer.Host 時出錯,說“需要對象引用...” - 但在optionsAccessor.Value上沒有出錯。

optionsAccessor.ValueoptionsAccessor.Value返回 MailServer 的一個實例嗎? 我在這里犯了一些菜鳥錯誤嗎?

MailServer類的屬性UseSSLbool但在 appsettings.json 中設置為"True"

您應該像這樣更改 appsettings.json:

"MailServer": {
  "Host": "smtp.gmail.com",
  "Port": 587,
  "UseSSL": true,
  "Username": "xxxxxxx@gmail.com",
  "Password": "xxxxxxx",
  "FromAddress": "xxxxxxx<xxxxxxx@gmail.com>"
}

編輯:我用這段代碼創建了一個空項目並編譯。 也許使用語句出錯或啟用了嚴格模式?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace samp
{
    public class MailServer
    {
        public string Host { get; set; }
        public int Port { get; set; }
        public bool UseSSL { get; set; }
        public string Username { get; set; }
        public string Password { get; set; }
        public string FromAddress { get; set; }
        public MailServer()
        {
        }
    }

    public interface IScheduledTask
    {
        void MonitorCloudHosts();
    }

    public class ScheduledTask : IScheduledTask
    {
        private readonly IServiceProvider _ServiceProvider;
        private readonly MailServer _mailServer;

        // note here you ask to the injector for IServiceProvider
        public ScheduledTask(IServiceProvider serviceProvider, IOptions<MailServer> optionsAccessor)
        {
            _ServiceProvider = serviceProvider;
            _mailServer = optionsAccessor.Value;
        }

        public void MonitorCloudHosts()
        {
            // Do some stuff
            var xyz = _mailServer.Host;
        }
    }

    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // 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.Configure<MailServer>(Configuration.GetSection("MailServer"));
            services.AddSingleton<IScheduledTask, ScheduledTask>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseMvc();
        }
    }
}

暫無
暫無

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

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