2

I am developing a blazor application. I want to have connection string and some other key in a class as service.

For that I have created an interface

interface IDbConnector
{
    string ConnectionString { get; set; }

    bool SomeKey { get; set; }
}

and in my class I want to have something like that

using Microsoft.Extensions.Configuration;
    public class DbConnector : IDbConnector
    {
        private IConfiguration Configuration { get; set; }

        public DbConnector(IConfiguration configuration)
        {
            Configuration = configuration;
        }
        public string ConnectionString = Configuration.GetConnectionString();

        public bool SomeKey = Configuration.GetSection("xyz");
    }

I can register it as a service with

services.AddScoped<IDbConnector, DbConnector>();

But inside DbConnector class it says

A fiels initializer can not refrence the non static field ,method or property DbConnector.Configuration

Pardon for my coding pattern as I am new to DI concept. Please suggest if there is another and better way to do this.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Saurabh
  • 1,505
  • 6
  • 20
  • 37
  • 1
    You can do `ConnectionString = configuration.GetConnectionString();` in your constructor. – JohanP Jun 16 '19 at 06:33
  • @JohanP , Error: ConnectionString does not exist in current context – Saurabh Jun 16 '19 at 06:36
  • You need to declare it. `public string ConnectionString {get;set;}` – JohanP Jun 16 '19 at 06:39
  • Possible duplicate of [Configure connection string from controller (ASP.NET Core MVC 2.1)](https://stackoverflow.com/questions/54490808/configure-connection-string-from-controller-asp-net-core-mvc-2-1) –  Jun 16 '19 at 08:11

2 Answers2

3

You've made a syntax error, these should be expression bodied property accessors. = to =>

public string ConnectionString => Configuration.GetConnectionString();

public bool SomeKey => Configuration.GetSection("xyz");

Instead you've tried to initialise them as fields. Fields initialise pre-constructor, therefore cannot access the configuration.

Avin Kavish
  • 8,317
  • 1
  • 21
  • 36
-1
      services.AddConfiguration()  // enable Configuration Services

       var config = new WeblogConfiguration();
       Configuration.Bind("Weblog", config);      //  <--- This
       services.AddSingleton(config);
  • 5
    While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. – Eric Leschinski Jun 17 '19 at 01:11