今天我正在尝试使用新的asp.net核心2.0,但是在使用我没有在IConfiguration配置构造函数属性中注入的JSON配置文件时遇到了一些麻烦。
在asp.net核心1.1中,我将在StartUp中使用以下代码:
public static IConfigurationRoot Configuration;
Public Startup(IHostingEnvironment env) {
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appSettings.json", optional: false, reloadOnChange: true)
Configuration = builder.Build();
}
可以从代码中访问它,如:
private string _mailTo = Startup.Configuration["mailSettings:mailToAddress"];
然而在Core 2.0中他们改为IConfiguration并且它已经定义了,而且我没有看到任何方式可以在我的其他课程中使用该配置,所以我对如何使用有点无能为力继续。
startupClass:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Mvc.Formatters;
using NLog.Web;
using NLog.Extensions.Logging;
using cityInfoTestApi.Services;
namespace cityInfoTestApi
{
public class Startup
{
public IConfiguration Configuration { get; private set; }
public Startup(IConfiguration configuration, IHostingEnvironment env)
{
Configuration = configuration;
env.ConfigureNLog("nlog.config");
}
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.AddMvcOptions(o => o.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter()));
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddNLog();
app.AddNLogWeb();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseStatusCodePages();
app.UseMvc();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
我的json文件:
{
"mailSetings": {
"mailToAddress": "admin@mycompany.com",
"mailFromAddress": "noreply@mycompany.com"
}
}
我想要使用设置的自定义类(请注意,我将如何使用核心1.1:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
namespace cityInfoTestApi.Services
{
public class LocalMailService : IMailService
{
private string _mailTo = Startup.Configuration["mailSettings:mailToAddress"];
private string _mailFrom = Startup.Configuration["mailSettings:mailFromAddress"];
public void Send(string subject, string message)
{
Debug.WriteLine($"Mail from {_mailFrom} to {_mailTo}, with LocalMailService");
Debug.WriteLine($"Subject: {subject}");
Debug.WriteLine($"Message: {message}");
}
}
}
任何帮助都会非常感谢,干杯!
答案 0 :(得分:6)
是的,ASP.NET Core 2.0改变了配置构建的方式。您现在需要使用IWebHostBuilder.ConfigureAppConfiguration
方法。
将这样的内容添加到Program.cs中的IWebHost
创建:
.ConfigureAppConfiguration((builderContext, config) =>
{
IHostingEnvironment env = builderContext.HostingEnvironment;
config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
})
然后IConfiguration
实例可以通过构造函数作为依赖项(或任何其他类,由于DI机制)注入到您的Startup
类中:
public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
...
}
有一篇很好的文章描述了这些变化:ASP.NET Core 2.0 Configuration Changes
关于从自定义类(如LocalMailService
)访问设置的方法 - 避免使用任何静态依赖项。这个破坏的DI概念在ASP.NET Core中使用。请阅读有关使用IOptions功能的信息。或者您可以再次使用DI并通过IConfiguration
中的ctor获取LocalMailService
实例。
答案 1 :(得分:3)
我认为您可以使用IOptions将配置文件传递给您的服务。 为您的配置创建一个类:
public class MailSetings
{
public string MailToAddress {get;set;}
public string MailFromAddress {get;set}
public class MailSetings() { }
}
配置服务以使用这些设置:
//...
using Microsoft.Extensions.Configuration;
//...
public class Startup
{
//..
public void ConfigureServices(IServiceCollection services)
{
services.Configure<MailSetings>(Configuration);
//...
}
现在您应该可以在服务构造函数中注入它:
//...
using Microsoft.Extensions.Options;
public class LocalMailService : IMailService
{
private string _mailTo;
private string _mailFrom;
public LocalMailService(IOptions<MailSetings> options)
{
_mailTo = options.Value.MailToAddress;
_mailFrom = options.Value.MailFromAddress;
}
//...
}