3

I have some appsetting.json below

{
  "MyConfig": {
    "FolderAnnouncement": "Duyuru\\",
    "BaseMediaUrl": "D:\\YoungTalent\\YTPanel\\YTPanel\\wwwroot\\images\\"
  },
  "ConnectionStrings": {
    "MySqlCon": "Server=localhost;Database=kariyer_portal;Uid=root;Pwd=1234;",
    "MsSqlCon": "Server=localhost\\SQLEXPRESS;Database=kariyer_portal;Trusted_Connection=True;ConnectRetryCount=0"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*"
}

And I have one class MyConfig.

namespace YTPanel.Models.Model
{
    public interface ITest { string GetFolders(string param); }
    public class MyConfig: ITest
    {
        public MyConfig(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        private readonly IConfiguration Configuration;


        public string BaseMediaUrl { get; set; }
        public string FolderAnnouncement { get; set; }

        public string GetFolders(string param)
        {

            string here = Configuration["MyConfig:" + param];
            return here; 
        }
    }   
}

I want to call this class from another class

MyConfig conf;
  private  string SaveAnnouncement(IFormFile file=null,string base64=null)
        {
            string path = conf.GetFolders("FolderAnnouncement");
            string imageUrl = Guid.NewGuid().ToString();
            var mediaPath = conf.GetFolders("BaseMediaUrl");
            string extension = Path.GetExtension(file.FileName);
            var imagePath = mediaPath + path + imageUrl+extension;
            if (!string.IsNullOrEmpty(base64))
            {
                byte[] bytes = Convert.FromBase64String(base64);
                File.WriteAllBytes(imagePath, bytes);  
            }
            else
            {
                using (var fileStream = new FileStream(imagePath, FileMode.Create))
                {
                    file.CopyToAsync(fileStream);
                }
            }
            return  imageUrl+extension;

        }

I added below to ConfigureServices in Startup.

services.AddSingleton<ITest, MyConfig>();

I can't reach the data . How can I solve this problem. I want to reacj appsetting json in one class and I use this class iin any classes I want.

Thanks in advance

4
  • When you say that you "can't reach the data," what does that literally mean? Is it throwing an exception, or something else? Commented Apr 4, 2019 at 17:19
  • @ScottHannen it returns null Commented Apr 4, 2019 at 17:45
  • if you want to access appsetting file without dependency refer this comment it will be helpful to you. stackoverflow.com/a/50147072/3595964 Commented Apr 4, 2019 at 18:33
  • You can see accept answer here stackoverflow.com/questions/50986497/… Commented Apr 5, 2019 at 6:22

3 Answers 3

11

There really is no need to be passing IConfiguration around. The framework already has built in features that allow you to bind an object model from values in setting

Create a simple class to hold your configuration.

public class MyConfig {
    public string BaseMediaUrl { get; set; }
    public string FolderAnnouncement { get; set; }
}

Setup your class in ConfigureServices in Startup.

//bind object model from configuration
MyConfig myConfig = Configuration.GetSection("MyConfig").Get<MyConfig>();

//add it to services
services.AddSingleton(myConfig);

And inject your strongly typed configuration class where it is needed

private readonly MyConfig conf;

//Constructor
public AnnouncementService(MyConfig config) {
    this.conf = config;
}

private async Task<string> SaveAnnouncement(IFormFile file = null, string base64 = null) {
    string path = conf.FolderAnnouncement;
    string imageUrl = Guid.NewGuid().ToString();
    var mediaPath = conf.BaseMediaUrl;
    string extension = Path.GetExtension(file.FileName);
    var imagePath = mediaPath + path + imageUrl+extension;
    if (!string.IsNullOrEmpty(base64)) {
        byte[] bytes = Convert.FromBase64String(base64);
        File.WriteAllBytes(imagePath, bytes);  
    } else {
        using (var fileStream = new FileStream(imagePath, FileMode.Create)) {
            await file.CopyToAsync(fileStream);
        }
    }
    return  imageUrl+extension;
}

Note how the magic strings are no longer needed. You can access the desired configuration values via the properties.

Reference Configuration in ASP.NET Core

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

1 Comment

Nice and simple way to deserialize appsettings.json to object. Somehow all the other examples I found so far on the web looked so complex.
3

In addition to @nkosi’s answer, the Options pattern works well for this:

services.Configure<MyConfig>(configuration.GetSection(“MyConfig”));

...

public class SomeClass
{
    private MyConfig _options;

    public SomeClass(IOptions<MyConfig> options)
    {
        _options = options.Value;
    }

    private async Task<string> SaveAnnouncement(IFormFile file = null, string base64 = null)
    {
        string path = _options.FolderAnnouncement;
        ...
    }
}

There are additional variants available if you need to catch live changes to appsettings.json; see the link.

Comments

2

Usually you would inject your MyTest class (by interface) and use it like this:

public class AnnouncementSaver {

  private ITest config;
  public AnnouncementSaver(ITest config) {
    // inject it
    this.config = config;
  }

  private string SaveAnnouncement (IFormFile file = null, string base64 = null) {
    // use it
    config.GetFolders("FolderAnnouncement");
  }

}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.