I need to perform a lot of initialization when bootstrapping my servers, just BEFORE they start listening to incoming calls. Many of these methods I have written are asynchronous.
Some of my init code runs in the Configure method, some are called in the AfterInitCallback
handler. Looks like I cannot await them. Here is a sample for my MongoDB initialization:
public override void Configure(Container container)
{
MongoDbClient = new MongoClient(Settings.Default.LicenseServerConnStr);
#region Redis database connection pools
// .... code here
#endregion
#region IOC registrations
// ..... code here
#endregion
#region Plugin registrations
// registering all required plugins
#endregion
#region ServiceStack Filters
// ... code here
#endregion
#region Scheduler setup
// code to init Quartz scheduler, contains ASYNC method calls
#endregion
#region RabbitMQ bus IOC registration
// code to init RabbitMQ stuff
#endregion
AfterInitCallbacks.Add(host =>
{
// .. code to setup configuration etc.
RegisterMongoDbRepos(container);
InitMongoDb(); // <<--- PROBLEM HERE, THIS NEEDS TO BE AWAITED!!
RegisterScheduledJobs(container);
RegisterMsgSubscriptions();
});
}
The InitMongoDb()
method calls tons of async
methods of a generic MongoDB operations class I have written:
private async Task InitMongoDb() //<<-- ASYNC method
{
var db = MongoDbClient.GetDatabase(LsConstants.LsDatabaseName);
var collectionNames = new List<string>();
// .. other code ....
try
{
var mongoOps = new MongoDbOperations(); <<--- THIS CLASS HAS TONS OF ASYNC METHODS
if (!collectionNames.Contains(LsConstants.PushMessageStoreCollection))
{
db.CreateCollection(LsConstants.PushMessageStoreCollection,
new CreateCollectionOptions
{
Collation = new Collation("en", false, CollationCaseFirst.Off, CollationStrength.Primary)
});
// AWAITED method that creates lots of indexes etc on the database
await mongoOps.CreatePushMessageStoreCollectionIndexes(LsConstants.LicenseDatabaseName, OperationExecutionType.EventDriven);
}
// lot more things with async/await methods .....
}
catch (Exception collex)
{
Log.Error($"Error creating collections in database '{LsConstants.LicenseDatabaseName}'. Error: {collex}");
throw;
}
}
Is there any way to call async methods in the Configure and the callback handler? I tried
AfterInitCallbacks.Add(async host =>
{
//...
await InitMongoDb();
// ...
});
This compiles but seems NOT to wait, my services are started BEFORE my init code has completed! Not what I want.