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

Ankit Mori
  • 705
  • 14
  • 23
mr. pc_coder
  • 16,412
  • 3
  • 32
  • 54
  • When you say that you "can't reach the data," what does that literally mean? Is it throwing an exception, or something else? – Scott Hannen Apr 04 '19 at 17:19
  • @ScottHannen it returns null – mr. pc_coder Apr 04 '19 at 17:45
  • if you want to access appsetting file without dependency refer this comment it will be helpful to you. https://stackoverflow.com/a/50147072/3595964 – Ankit Mori Apr 04 '19 at 18:33
  • You can see accept answer here https://stackoverflow.com/questions/50986497/get-appsettings-json-values-in-service-net-core/51006614#51006614 –  Apr 05 '19 at 06:22

3 Answers3

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

Nkosi
  • 235,767
  • 35
  • 427
  • 472
  • 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. – coder Jul 17 '20 at 02:14
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.

sellotape
  • 8,034
  • 2
  • 26
  • 30
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");
  }

}
Edub
  • 508
  • 7
  • 24