Home > OS >  ServiceStack IAppSettings was not ready and would result NULL reference exception if used in constru
ServiceStack IAppSettings was not ready and would result NULL reference exception if used in constru

Time:03-24

It seems like the IAppSettings implementation was not ready from IoC in the constructor.

Before I go into details, I've read similar problems:

  • enter image description here

    What I have

    All my codes are in the repo: // TODO: attach screenshot

    What doesn't work

    When you're trying to get the IAppSettings and initialize something else with some app setting values in the constructor - whether it's in the child class or the base class, IAppSettings will fail to get the implementation from IoC, and result a NULL reference exception:

    public abstract class ServiceBase : Service
    {
        public IAppSettings AppSettings { get; set; }
    
        public ServiceBase()
        {
            // AppSettings would be NULL
            var test = AppSettings.Get<string>("custom");
        }
    }
    

    OR

    public class HelloService : ServiceBase
    {
        public HelloService()
        {
            // AppSettings would be NULL
            var test = AppSettings.Get<string>("custom");
        }
    }
    

    // TODO: attach screenshots

    CodePudding user response:

    You cannot use any property dependency in the constructor since the properties can only be injected after the class is created and the constructor is run.

    You'll only be able to access it in the Constructor by using constructor injection, e.g:

    public class HelloService : ServiceBase
    {
        public HelloService(IAppSettings appSettings)
        {
            var test = appSettings.Get<string>("custom");
        }
    }
    

    Or accessing the dependency via the singleton:

    public class HelloService : ServiceBase
    {
        public HelloService()
        {
            var test = HostContext.AppSettings.Get<string>("custom");
        }
    }
    
  • Related