A streamlined and efficient service for interacting with Azure Cosmos DB in ASP.NET Core applications.
- Retrieve Documents: Fetch specific documents from a Cosmos DB container.
- Create Documents: Insert new items into a container.
- List Documents: Query and retrieve multiple documents.
- Update Documents: Replace existing items with updated data.
- Delete Documents: Remove items by their document ID.
- Configurable: Easily integrates with your app's configuration system.
You are free to download, change and use it anywhere. I will regularly update this template with new resources and pages I found on the web. Don't hesitate to participate by sending a PR! Maybe your first on Github :)
If you like this resource, please follow me on GitHub. Thank you!
- .NET 9.0+
- Azure Cosmos DB Account
- Azure SDK: Ensure you have the
Microsoft.Azure.Cosmos
NuGet package installed.
Add the required NuGet package to your project:
dotnet add package Microsoft.Azure.Cosmos
Include the CosmosService
class in your project and configure it as a service.
Add the following settings to your appsettings.json
file:
{
"CosmosDbEndpoint": "https://your-cosmos-account.documents.azure.com:443/",
"CosmosDbKey": "your-cosmos-primary-key",
"CosmosDbName": "your-database-name"
}
Register CosmosService
in your dependency injection container:
services.AddSingleton<ICosmosService, CosmosService>();
Use it in your controllers or services:
public class MyController : ControllerBase
{
private readonly ICosmosService _cosmosService;
public MyController(ICosmosService cosmosService)
{
_cosmosService = cosmosService;
}
[HttpGet("document/{id}")]
public async Task<IActionResult> GetDocument(string id)
{
var document = await _cosmosService.GetDocumentAsync<MyDocument>("my-container", id);
return document is not null ? Ok(document) : NotFound();
}
}
await cosmosService.GetDocumentAsync<MyType>("containerName", "documentId");
await cosmosService.CreateDocumentAsync("containerName", new MyType { ... });
await cosmosService.ListDocumentsAsync<MyType>("containerName", "SELECT * FROM c");
await cosmosService.ReplaceDocumentAsync("containerName", "documentId", updatedItem);
await cosmosService.DeleteDocumentAsync<MyType>("containerName", "documentId");
If you would like to contribute, please create a new branch and submit a pull request with your changes. Review may be needed before acceptance.
@cenksari
MIT