-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConfig.cs
59 lines (51 loc) · 2.24 KB
/
Config.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
using System;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Domain.SeedWork;
using EventStore.Client;
using Infrastructure.Repositories;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Serializers;
using MongoDB.Driver;
namespace Infrastructure
{
public static class Config
{
public static void AddEventStoreDbContext(this IServiceCollection services, IConfiguration configuration) {
var connectionUri = configuration.GetConnectionString("dabit-event-store-db");
services.AddSingleton(new EventStoreClient(EventStoreClientSettings.Create(connectionUri)));
}
public static void AddMongoDbContext(this IServiceCollection services, IConfiguration configuration) {
var connectionUri = configuration.GetConnectionString("dabit-mongo-db");
var client = new MongoClient(connectionUri);
var database = client.GetDatabase("dabit");
BsonSerializer.RegisterSerializer(typeof(DateTime), new DateTimeSerializer(DateTimeKind.Local));
services.AddSingleton(database);
}
public static void AddMongoRepository<TView>(
this IServiceCollection services,
string name,
Action<IMongoCollection<TView>>? options = null
)
where TView : IIdentifiable {
services.AddScoped<IMongoCollection<TView>>(provider =>
{
var db = provider.GetRequiredService<IMongoDatabase>();
var collection = db.GetCollection<TView>(name);
options?.Invoke(collection);
return collection;
});
services.AddScoped<IMongoRepository<TView>, MongoRepository<TView>>();
}
public static async Task AddGuidIndex<TDocument>(
this IMongoCollection<TDocument> collection,
Expression<Func<TDocument, object>> field
) {
var indexDefinition = Builders<TDocument>.IndexKeys.Ascending(field);
var indexModel = new CreateIndexModel<TDocument>(indexDefinition);
await collection.Indexes.CreateOneAsync(indexModel);
}
}
}