Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 484
mr. pc_coder Avatar asked Aug 24 '26 15:08

mr. pc_coder


1 Answers

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

like image 117
Nkosi Avatar answered Aug 27 '26 06:08

Nkosi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!