编码时,差异浮出水面。通常在编写简单方法或构造函数时,我经常使用表达体技术。但是,当我产生以下内容时:
public class Sample : ISample
{
private readonly IConfigurationRoot configuration;
public Sample(IConfigurationRoot configuration) => this.configuration = configuration;
}
代码似乎是有效的,Visual Studio和编译都工作。虽然问题出现在同一个类中,但我会使用configuration
变量。它产生“字段初始值设定项不能引用非静态字段初始值设定项。”
产生的语法用法:
var example = configuration.GetSection("Settings:Key").Value;
但是,如果我将片段留在此上方并修改为块体。 Visual Studio不再吓坏了,为什么表达体会导致如此特殊的错误?块体正常与上面的片段一起工作吗?
public class Sample : ISample
{
private readonly IConfigurationRoot configuration;
public Sample(IConfigurationRoot configuration)
{
this.configuration = configuration;
}
}
public class ApplicationProvider
{
public IConfigurationRoot Configuration { get; } = CreateConfiguration();
public IServiceProvider BuildProvider()
{
var services = new ServiceCollection();
DependencyRegistration(services);
return services.AddLogging().BuildServiceProvider();
}
private IConfigurationRoot CreateConfiguration() => new ConfigurationBuilder()
.SetBasePath(AppContext.BaseDirectory)
.AddJsonFile("appsettings.json")
.Build();
private void DependencyRegistration(this IServiceCollection services)
{
services.AddSingleton(_ => Configuration);
// All other dependency registration would also go here.
}
}
public static IServiceProvider ServiceProvider { get; } = new ApplicationProvider().BuildProvider();
我会为类创建一个接口,然后通过从提供程序中提取来实例化。
ISample sample = ServiceProvider.GetServices<ISample>();
答案 0 :(得分:-1)
public IConfigurationRoot Configuration { get; } = CreateConfiguration();
你没有设置属性,但是你试图设置它? 这对我来说很奇怪。