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.

4
  • 1
    You can do ConnectionString = configuration.GetConnectionString(); in your constructor. Commented Jun 16, 2019 at 6:33
  • @JohanP , Error: ConnectionString does not exist in current context Commented Jun 16, 2019 at 6:36
  • You need to declare it. public string ConnectionString {get;set;} Commented Jun 16, 2019 at 6:39
  • Possible duplicate of Configure connection string from controller (ASP.NET Core MVC 2.1) Commented Jun 16, 2019 at 8:11

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

-1
      services.AddConfiguration()  // enable Configuration Services

       var config = new WeblogConfiguration();
       Configuration.Bind("Weblog", config);      //  <--- This
       services.AddSingleton(config);

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.