I am trying to create cosmos Db database and collection on startup.cs of my microService. I have tried 2 approaches. One is to create a static extension method for service and do the initialization for cosmos db there. The other approach is to just create a singleton(ICosmosDbInitializer) and do the initialization in the constructor by using getAawaiter().Getresult() since database and collection creation methods are async.
I have also created an Ioption to save cosmos db configuration like databaseName, DbUrl, Accesskey etc.
services.Configure<CosmosDbOptions>((cosmosDbOptions) =>
{
// more code here
});
My issue is that I am unable to inject this Option to either static extension method or singelton.
1. Using Static extension method
Inside Startup.cs
//Not sure how to pass cosmosDbOptions here
services.ConfigureCosmosDbClient(???);
Inside static extension class
public static IServiceCollection ConfigureCosmosDbClient(this IServiceCollection services, CosmosDbOptions cosmosDbOptions)
{
}
2. Using Warmed up singelton. Need to create warmup singleton so that database and collection is created before first user request. Here it fails at runtime when trying to inject Iptions.
Inside startup.cs
services.AddSingleton<CosmosDbInitializer, CosmosDbInitializer>();
public void Configure(IApplicationBuilder app)
{
app.ApplicationServices.GetService<CosmosDbInitializer>();
}
Inside singleton
public CosmosDbInitializer(CosmosDbOptions cosmosDbOptions) :
{
}
EDIT: Added error (from comments)
System.InvalidOperationException: 'Unable to resolve service for type 'CosmosDbOptions' while attempting to activate 'CosmosDbInitializer
You registered your options as TOptions
not like Service
. It tell you your log error message.
Try change
public static IServiceCollection ConfigureCosmosDbClient(this IServiceCollection services, CosmosDbOptions cosmosDbOptions)
{
}
to
public static IServiceCollection ConfigureCosmosDbClient(this IServiceCollection services, IOptionsMonitor<CosmosDbOptions> cosmosDbOptions)
IOptionsMonitor is used to retrieve options and manage options notifications for TOptions instances.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.