While coding, a discrepancy surfaced. Normally while coding simple methods or constructors I often utilize the expression body technique. However, when I produce the following:
public class Sample : ISample
{
private readonly IConfigurationRoot configuration;
public Sample(IConfigurationRoot configuration) => this.configuration = configuration;
}
The code appears to be valid, Visual Studio and compile both work. The issue though comes if inside that same class, I go to use the configuration
variable. It produces "A field initializer cannot reference a non static field initializer."
That syntax usage that produced:
var example = configuration.GetSection("Settings:Key").Value;
However, if I leave the snippet above this and modify to a block body. Visual Studio no longer freaks out, why would an expression body cause such a peculiar error? While the block body works correctly with snippet above?
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();
I would have an interface for class, then instantiate by pulling from the provider.
ISample sample = ServiceProvider.GetServices<ISample>();
var
anyway. – Sizedvar
comment, the example I have with avar
is trying to read the field to retrieve the value. Not per se use. Could you clarify please? – Aquinoexample
, which you can't do using var if you're trying to make that variable a field. Basically, we're guessing what your code really looks like because you haven't provided us with a minimal reproducible example. It's easy to stop the speculation: provide a complete example. – Sizedvar example
line was a member function or something similar. Also, if you are using a framework to perform the dependency injection for you -- as suggested by your comments -- that is important to know. – Fluidextractpublic static IServiceProvider ServiceProvider { get; } = new ApplicationProvider().BuildProvider();
doesn't work. – Fluidextractstatic
is in a whole different class. – AquinoA field initializer cannot reference the non-static field, method, or property
If so, it's this line that is the problem:public IConfigurationRoot Configuration { get; } = CreateConfiguration();
– Fluidextract