【发布时间】:2015-10-27 14:18:19
【问题描述】:
我正在尝试创建一个新的 ASP.Net MV5 项目(目前为 beta8),用于学习目的。
我对获取应用设置的简单案例感到困惑。
我在 appsettings.json 文件中添加了一些配置:
{
"Data": {
"DefaultConnection": {
"ConnectionString": "Server=(localdb)\\mssqllocaldb;Database=aspnet5-someproject-e84e86e2-0fec-4132-9a91-2f6c4b4c61a3;Trusted_Connection=True;MultipleActiveResultSets=true"
}
},
"AppSettings": {
"CloudStorageContainerReference": "someproject",
"StorageConnectionString": "UseDevelopmentStorage=true"
}
}
我还创建了一个强类型类:
public class AppSettings
{
public string CloudStorageContainerReference { get; set; }
public string StorageConnectionString { get; set; }
}
并更新了我的启动文件:
public void ConfigureServices(IServiceCollection services)
{
// Add Entity Framework services to the services container.
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));
// Add Identity services to the services container.
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
// Add settings
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
// Add MVC services to the services container.
services.AddMvc();
// Register application services.
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
}
此时,如果我破解代码,我可以看到Configuration.GetSection("AppSettings").Value 为空。
此外,我想在我的控制器中注入这些设置:
public class TransfertController : Controller
{
private IOptions<AppSettings> AppSettings;
public TransfertController(IOptions<AppSettings> appSettings)
{
if (AppSettings == null) throw new ArgumentNullException(nameof(appSettings));
AppSettings = appSettings;
}
}
但它会抛出一个NullReferenceException,因为我的appSettings 参数为空。
缺少什么?
[编辑]:作为旁注,这一行:
Configuration["AppSettings:CloudStorageContainerReference"]
实际上返回正确的单个值。
【问题讨论】:
标签: asp.net dependency-injection asp.net-core-mvc