Monday, September 25, 2017

How to use OrmLiteAppSettings ServiceStack - Manage configs in database - C#

## AppSettings

### New OrmLiteAppSettings

Added new read/write AppSettings config option utilizing OrmLite as the back-end. 
This now lets you maintain your applications configuration in any [RDBMS back-end OrmLite supports](https://github.com/ServiceStack/ServiceStack.OrmLite/#download). It basically works like a mini Key/Value database in which can store any serializable value against any key which is maintained into the simple Id/Value `ConfigSettings` table.

#### Usage

Registration just uses an OrmLite DB Factory, e.g:

```csharp
container.Register(c => new OrmLiteAppSettings(c.Resolve<IDbConnectionFactory>()));
var appSettings = container.Resolve<OrmLiteAppSettings>();
appSettings.InitSchema(); //Create the ConfigSettings table if it doesn't exist
```
It then can be accessed like any [AppSetting APIs](https://github.com/ServiceStack/ServiceStack/blob/master/tests/ServiceStack.Common.Tests/Configuration/AppSettingsTests.cs):

```csharp
//Read the `MyConfig` POCO stored at `config` otherwise use default value if it doesn't exist
MyConfig config = appSettings.Get("config", new MyConfig { Key = "DefaultValue" });
```

It also supports writing config values in addition to the AppSettings read-only API's, e.g:

```csharp
var latestStats = appSettings.GetOrCreate("stats", () => statsProvider.GetLatest());
```

### Extract key / value settings from text file

The new ParseKeyValueText extension method lets you extract key / value data from text, e.g: 

Use in Controller:

 public class TestController : BaseController  
 {  
      private readonly OrmLiteAppSettings _appsettings;  
      private readonly ILifetimeScope _lifetimeScope;  
      public SimManageController(ILifetimeScope lifetimeScope)  
      {  
           _lifetimeScope = lifetimeScope;  
           _appsettings = _lifetimeScope.Resolve<OrmLiteAppSettings>();  
           var keys = _appsettings.GetAllKeys();  
      }  
 }  

No comments:
Write comments