Cagri Tacyildiz
Cagri Tacyildiz

Reputation: 17610

Get Value from appsetting.json in class

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

Upvotes: 3

Views: 10956

Answers (3)

sellotape
sellotape

Reputation: 8325

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.

Upvotes: 3

Nkosi
Nkosi

Reputation: 247133

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

Upvotes: 11

Edub
Edub

Reputation: 540

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");
  }

}

Upvotes: 2

Related Questions