ISC.MongoDB.Extensions.DependencyInjection
1.0.2
dotnet add package ISC.MongoDB.Extensions.DependencyInjection --version 1.0.2
NuGet\Install-Package ISC.MongoDB.Extensions.DependencyInjection -Version 1.0.2
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="ISC.MongoDB.Extensions.DependencyInjection" Version="1.0.2" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="ISC.MongoDB.Extensions.DependencyInjection" Version="1.0.2" />
<PackageReference Include="ISC.MongoDB.Extensions.DependencyInjection" />
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add ISC.MongoDB.Extensions.DependencyInjection --version 1.0.2
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
#r "nuget: ISC.MongoDB.Extensions.DependencyInjection, 1.0.2"
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package ISC.MongoDB.Extensions.DependencyInjection@1.0.2
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=ISC.MongoDB.Extensions.DependencyInjection&version=1.0.2
#tool nuget:?package=ISC.MongoDB.Extensions.DependencyInjection&version=1.0.2
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
ISC.MongoDB.Extensions.DependencyInjection
A lightweight library that registers IMongoDBConnection into Dependency Injection for MongoDB access in .NET applications.
Installation
dotnet add package ISC.MongoDB.Extensions.DependencyInjection
Requirements
- .NET 8+
MongoDB.Driver(already referenced by this package)
Usage
1) Quick registration with connection string
using ISC.MongoDB.Extensions.DependencyInjection;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddMongoDB(
connectionString: builder.Configuration.GetConnectionString("MongoDB")!,
database: "MyDatabase",
timeout: 10);
2) Customize MongoClientSettings during registration
using ISC.MongoDB.Extensions.DependencyInjection;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddMongoDB(
connectionString: builder.Configuration.GetConnectionString("MongoDB")!,
database: "MyDatabase",
timeout: 10,
configureSettings: settings =>
{
settings.RetryReads = true;
settings.RetryWrites = true;
settings.MaxConnectionPoolSize = 200;
settings.ApplicationName = "MyApi";
});
3) Create MongoClientSettings manually and pass it in
using ISC.MongoDB.Extensions.DependencyInjection;
using MongoDB.Driver;
var builder = WebApplication.CreateBuilder(args);
var settings = MongoClientSettings.FromConnectionString(
builder.Configuration.GetConnectionString("MongoDB")!);
builder.Services.AddMongoDB(
settings: settings,
database: "MyDatabase",
timeout: 10,
configureSettings: s =>
{
s.ConnectTimeout = TimeSpan.FromSeconds(5);
s.ServerSelectionTimeout = TimeSpan.FromSeconds(5);
s.SocketTimeout = TimeSpan.FromSeconds(30);
});
Sample appsettings.json
{
"ConnectionStrings": {
"MongoDB": "mongodb://localhost:27017"
}
}
IMongoDBConnection API
Task<bool> InsertDocumentAsync(BsonDocument document, string collectionName);Task<bool> InsertListDocumentsAsync(List<BsonDocument> documents, string collectionName);Task<BsonDocument> GetDocumentAsync(FilterDefinition<BsonDocument> filter, string collectionName, FindOptions<BsonDocument>? options = null);Task<List<BsonDocument>> GetListDocumentsAsync(FilterDefinition<BsonDocument> filter, string collectionName, FindOptions<BsonDocument>? options = null);Task<List<BsonDocument>> GetAggregateAsync(List<BsonDocument> pipeline, string collectionName, AggregateOptions? options = null);Task<int> CountDocumentsAsync(FilterDefinition<BsonDocument> filter, string collectionName);Task<int> DeleteDocumentsAsync(FilterDefinition<BsonDocument> filter, string collectionName);DeleteAsync
Notes
timeoutis the default connection timeout used by this package.- You can override or extend advanced client options through
configureSettings.
Ponus Function get GetAggregateAsync
using ISC.MongoDB.Extensions.DependencyInjection;
using MongoDB.Bson;
using MongoDB.Driver;
public class ReportRepository : IReportRepository
{
private IMongoDBConnection _mongoDBConnection;
public ReportRepository(IMongoDBConnection mongoDBConnection)
{
_mongoDBConnection = mongoDBConnection;
}
public async Task<(List<OutputMessageDTO> Data, int Total)> GetPipelineMessageDeliveriesAsync(int pageNumber,
int pageSize, string channel, string? state, List<Guid> clientId, string? Vendor, DateTimeOffset? fromDate, DateTimeOffset? toDate,
List<Guid>? validClientIds = null, List<Guid>? validVendorIds = null, List<Guid>? validVendorAccountIds = null)
{
try
{
string colectionName = GetCollectionName(channel);
var pipeline = new List<BsonDocument>();
// MATCH filter
var matchConditions = new BsonDocument();
// Merge clientId parameter with validClientIds for filtering
var finalClientIds = new List<Guid>();
if (clientId != null && clientId.Count > 0)
finalClientIds.AddRange(clientId);
if (validClientIds != null && validClientIds.Count > 0)
{
if (finalClientIds.Count > 0)
finalClientIds = finalClientIds.Intersect(validClientIds).ToList();
else
finalClientIds = validClientIds;
}
if (finalClientIds.Count > 0)
{
matchConditions.Add("ClientId", new BsonDocument("$in", new BsonArray(finalClientIds)));
}
if (!string.IsNullOrEmpty(channel))
matchConditions.Add("Channel", channel);
if (!string.IsNullOrEmpty(state))
matchConditions.Add("State", state);
// Handle Vendor with validVendorIds
if (!string.IsNullOrEmpty(Vendor))
{
if (validVendorIds != null && validVendorIds.Count > 0)
{
// Check if Vendor parameter is in validVendorIds
if (Guid.TryParse(Vendor, out Guid vendorGuid) && validVendorIds.Contains(vendorGuid))
matchConditions.Add("Vendor", Vendor);
// else: skip this condition as vendor is not valid
}
else
{
matchConditions.Add("Vendor", Vendor);
}
}
else if (validVendorIds != null && validVendorIds.Count > 0)
{
matchConditions.Add("Vendor", new BsonDocument("$in", new BsonArray(validVendorIds)));
}
// Handle VendorAccountId with validVendorAccountIds
if (validVendorAccountIds != null && validVendorAccountIds.Count > 0)
{
matchConditions.Add("VendorAccountId", new BsonDocument("$in", new BsonArray(validVendorAccountIds)));
}
// Collect all $expr conditions to combine them
var exprConditions = new List<BsonDocument>();
// Filter date range
if (fromDate != null || toDate != null)
{
if (fromDate != null && toDate != null)
{
// When both dates are provided, check if date is between them (inclusive)
exprConditions.Add(
new BsonDocument("$and", new BsonArray
{
new BsonDocument("$gte", new BsonArray
{
new BsonDocument("$dateToString", new BsonDocument
{
{ "format", "%Y-%m-%d" },
{ "date", "$RequestTime" }
}),
fromDate.Value.ToString("yyyy-MM-dd")
}),
new BsonDocument("$lte", new BsonArray
{
new BsonDocument("$dateToString", new BsonDocument
{
{ "format", "%Y-%m-%d" },
{ "date", "$RequestTime" }
}),
toDate.Value.ToString("yyyy-MM-dd")
})
})
);
}
else if (fromDate != null)
{
// When only fromDate is provided
exprConditions.Add(
new BsonDocument("$gte", new BsonArray
{
new BsonDocument("$dateToString", new BsonDocument
{
{ "format", "%Y-%m-%d" },
{ "date", "$RequestTime" }
}),
fromDate.Value.ToString("yyyy-MM-dd")
})
);
}
else if (toDate != null)
{
// When only toDate is provided
exprConditions.Add(
new BsonDocument("$lte", new BsonArray
{
new BsonDocument("$dateToString", new BsonDocument
{
{ "format", "%Y-%m-%d" },
{ "date", "$RequestTime" }
}),
toDate.Value.ToString("yyyy-MM-dd")
})
);
}
}
// Add combined $expr condition if we have any
if (exprConditions.Count > 0)
{
if (exprConditions.Count == 1)
{
matchConditions.Add("$expr", exprConditions[0]);
}
else
{
matchConditions.Add("$expr", new BsonDocument("$and", new BsonArray(exprConditions)));
}
}
pipeline.Add(new BsonDocument("$match", matchConditions));
// 2) $facet Total + Data
pipeline.Add(
new BsonDocument("$facet",
new BsonDocument
{
{
"Items",
new BsonArray
{
// GROUP
new BsonDocument("$group",
new BsonDocument
{
{ "_id",
new BsonDocument
{
{ "ClientId", "$ClientId" },
{ "Vendor", "$Vendor" },
{ "VendorAccountId",
new BsonDocument("$ifNull", new BsonArray { "$VendorAccountId", "" })
}
}
},
{ "TotalMessage", new BsonDocument("$sum", 1) },
{ "TotalMessageSuccess",
new BsonDocument("$sum",
new BsonDocument("$cond",
new BsonArray { new BsonDocument("$eq", new BsonArray { "$State", "Success" }), 1, 0 }
)
)
},
{ "TotalMessageFail",
new BsonDocument("$sum",
new BsonDocument("$cond",
new BsonArray { new BsonDocument("$eq", new BsonArray { "$State", "False" }), 1, 0 }
)
)
}
}
),
// PROJECT
new BsonDocument("$project",
new BsonDocument
{
{ "_id", 0 },
{ "ClientId", "$_id.ClientId" },
{ "Vendor", "$_id.Vendor" },
{ "VendorAccountId", "$_id.VendorAccountId" },
{ "TotalMessage", 1 },
{ "TotalMessageSuccess", 1 },
{ "TotalMessageFail", 1 }
}
),
// SORT
new BsonDocument("$sort", new BsonDocument("TotalMessage", -1)),
// Paging
new BsonDocument("$skip", (pageNumber - 1) * pageSize),
new BsonDocument("$limit", pageSize)
}
},
{
"Total",
new BsonArray
{
new BsonDocument("$group",
new BsonDocument
{
{ "_id",
new BsonDocument
{
{ "ClientId", "$ClientId" },
{ "Vendor", "$Vendor" },
{ "VendorAccountId",
new BsonDocument("$ifNull", new BsonArray { "$VendorAccountId", "" })
}
}
}
}
),
new BsonDocument("$count", "Total")
}
}
}
)
);
var resultDocs = await _mongoDBConnection.GetAggregateAsync(pipeline, colectionName);
if (resultDocs.Count == 0)
return (new List<OutputMessageDTO>(), 0);
var facetResult = resultDocs[0];
// ITEMS
var items = facetResult["Items"].AsBsonArray
.Select(doc =>
{
int total = doc["TotalMessage"].ToInt32();
int success = doc["TotalMessageSuccess"].ToInt32();
double rateSuccess = total == 0
? 0
: Math.Round((double)success / total * 100, 2);
return new OutputMessageDTO(
channel,
AsGuidSafe(doc["Vendor"]),
AsGuidSafe(doc["ClientId"]),
AsGuidSafe(doc["VendorAccountId"]),
total,
success,
doc["TotalMessageFail"].ToInt32(),
0,
(rateSuccess + "%")
);
}).ToList();
// TOTAL
int total = 0;
var totalArray = facetResult["Total"].AsBsonArray;
if (totalArray.Count > 0)
total = totalArray[0]["Total"].ToInt32();
return (items, total);
}
catch (Exception ex)
{
throw new Exception("Function GetMessageDeliveriesAsync error:" + ex.Message);
}
}
}
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
-
net8.0
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 8.0.2)
- MongoDB.Driver (>= 2.28.0)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.