我想配置 .NET Core 2.0 CONSOLE 应用程序。有一行不会编译(请参阅我在代码中的说明)。
我检查了很多博客,网站等。这似乎是一种配置.NET Core应用程序的认可方式。我错过了汇编参考吗?
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using System;
using System.IO;
namespace fbs.Console
{
class Program
{
public static IConfiguration configuration;
public static IServiceProvider serviceProvider;
static void Main(string[] args)
{
// Create service collection
ConfigureServices();
var dbService = serviceProvider.GetRequiredService<IDbContext>();
}
private static void ConfigureServices()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
configuration = builder.Build();
var appSettings = new AppSettings();
var section = configuration.GetSection("AppSettings");
IServiceCollection services = new ServiceCollection();
services.AddOptions();
// The following statement does NOT compile???
services.Configure<AppSettings>(section);
services.AddSingleton<IDbContext, DbContext>();
serviceProvider = services.BuildServiceProvider();
}
}
public class AppSettings
{
public string Database { get; set; }
}
public interface IDbContext
{
string Database { get; set; }
}
public class DbContext : IDbContext
{
public string Database { get; set; }
public DbContext(IOptions<AppSettings> appSettings)
{
this.Database = appSettings.Value.Database;
}
}
}
修改: 编译器错误说:
Error CS1503 Argument 2: cannot convert from 'Microsoft.Extensions.Configuration.IConfigurationSection' to 'System.Action<fbs.Console.AppSettings'.
为了复制问题,只需创建一个新的.NET Core 2.0控制台应用程序,复制并粘贴我的代码并尝试编译。
答案 0 :(得分:1)
<强>解决:强>
事实上,我错过了将Microsoft.Extensions.Options.ConfigurationExtensions
添加到项目中。我不知道这个程序集是必要的,因为似乎不需要将它添加为“using”子句。至少,我的代码现在通过仅使用NuGet添加包来编译(但是对using语句没有任何更改)。我有点困惑。