Accessing AppConfig settings via Injection

Viewed 110

I have values in my AppConfig like this...

<appSettings>
<add key="id" value="1234" />
</appSettings>

In the IAppConfig class I have...

 public interface IAppConfig
 {
    string id{ get; }
 }
   
   [ConfigurationProperty("id")]
    public string id
    {
        get
        {
            return (string)this["id"];
        }
        set
        {
            this["id"] = value;
        }
    }

In a startup class I have

using SimpleInjector;

   public static Container Container;

    public static void Start()
    {
        Container = new Container();

         IAppConfig appConfig = (IAppConfig)ConfigurationManager.GetSection("appSettings");
         Container.Register<IAppConfig, AppConfig>(Lifestyle.Singleton);

    }

And I inject it into another class...

       private readonly IAppConfig config;

    public ClassName(IAppConfig config)
    {
        this.config = config;
        
    }

However the id (and other values) come up as empty strings. This happens in the Getter. I am calling the Start method before trying to access them. What am I doing wrong?

2 Answers

You register type AppConfig as singleton implementation of type IAppConfig, so when you request IAppConfig from container, you'll get an instance created by container, and not 'appConfig' you created in Start. You need to register instance like:

Container.Instance<IAppConfig>(appConfig);

You have created an appconfig object but have not registered that for injection.

Try the below:

Simplify you AppConfig class

 public class AppConfig
 {
    public string id{ get; set; }
 }

 var appconfig = new AppConfig{ id = ConfigurationManager.AppSettings["id"] };
 
container.Register<AppConfig>(() => appconfig, Lifestyle.Singleton);

You can keep the Interface pattern as well

Related