Service Initialization


I have a Service which needs to initialize some settings on start up.

I gather that the IOC framework prevents me from using a constructor if I want automatic registration features of Service Stack to work.

namespace MyProject.ServiceInterface
    public class HelloService : Service
        public string MySetting {get;set;}
        public object Get(MyGetRequest request) {

          //clearly I don't want to do this
          if(MySetting.Length == 0)
            MySetting = this.TryResolve<IAppSettings>().GetString("MySettingValue");
          return "Hello " + MySetting;

Where can I initialize the value for MySetting such that its ready the first time MyGetRequest is made?

Sorry if this is a basic question, but my Google-Fu is failing me here



If you make the string static you could initialize it with:

static string setting;
public static string MySetting => 
    setting ?? (setting = HostContext.Resolve<IAppSettings>().GetString("MySetting"));

But my recommendation would be to extract all your App Settings into a strong typed POCO and inject that into your Services that need it, e.g:

class AppConfig
    public string MySetting { get; set; }


public void Configure(Container container)
    container.Register(new AppConfig {
        MySetting = AppSettings.GetString("MySettingValue")

Which Services that need it can access with:

public class HelloService : Service
    public AppConfig AppConfig { get; set; }

    public object Get(MyGetRequest request) => $$"Hello {AppConfig.MySetting}";

Hello Mythz,

Thanks as always for your response!

The problem that I’m trying to solve actually doesn’t have too much to do with App Settings.

My principal problem is that I have multiple OrmLiteConnectionFactory objects which connect to different data sources.

Previously I solved this by having a Service constructor accept a few Connection Factories. This isn’t great though because I can’t use the auto-registration features of ServiceStack.

I’m not sure how to register multiple instances of OrmLiteConnectionFactory such that I can easily refer to them individually.



Are you registering Named Connections for your different OrmLite connections?


No. No I’m not. (Hangs head in shame)

This looks like the perfect solution to my problem.

Thanks so much!