Encoding detected a mismatch. Usually when coding simple methods or constructors, I often use the technique of expressing an expression. However, when I create the following:
public class Sample : ISample { private readonly IConfigurationRoot configuration; public Sample(IConfigurationRoot configuration) => this.configuration = configuration; }
The code seems valid, Visual Studio and compile both works. The problem, although it arises if inside the same class, I use the configuration variable. It creates "The field initializer cannot reference the non-static field initializer."
The syntax used is:
var example = configuration.GetSection("Settings:Key").Value;
However, if I leave a fragment above it and modify the body of the block. Visual Studio is no longer worried, why does the body of the expression cause such a strange error? While the body of the block is working correctly with the fragment 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);
I will have an interface for the class, and then instantiate by pulling from the provider.
ISample sample = ServiceProvider.GetServices<ISample>();
source share