-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathExtensions.cs
More file actions
61 lines (52 loc) · 2.33 KB
/
Extensions.cs
File metadata and controls
61 lines (52 loc) · 2.33 KB
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
60
61
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection.Extensions;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Serializers;
using uBeac;
using uBeac.Repositories;
using uBeac.Repositories.MongoDB;
namespace Microsoft.Extensions.DependencyInjection;
public static class RepositoryExtensions
{
public static IServiceCollection AddMongo<TMongoDbContext>(this IServiceCollection services, string connectionString)
where TMongoDbContext : class, IMongoDBContext
{
services.TryAddSingleton(provider =>
{
var configuration = provider.GetService<IConfiguration>();
var connString = configuration.GetConnectionString(connectionString);
return new MongoDBOptions<TMongoDbContext>(connString);
});
services.TryAddSingleton<TMongoDbContext>();
services.TryAddSingleton<IMongoDBContext, TMongoDbContext>();
services.TryAddSingleton(provider =>
{
var appContextType = provider.CreateScope().ServiceProvider.GetRequiredService<IApplicationContext>().GetType();
return new BsonSerializationOptions
{
Serializers = new Dictionary<Type, IBsonSerializer>
{
{ typeof(Guid), new GuidSerializer(GuidRepresentation.Standard) },
{ typeof(decimal), new DecimalSerializer(BsonType.Decimal128) },
{ typeof(decimal?), new NullableSerializer<decimal>(new DecimalSerializer(BsonType.Decimal128)) },
{ typeof(IApplicationContext), new AppContextBsonSerializer(appContextType) }
},
GuidRepresentationMode = GuidRepresentationMode.V3
};
});
return services;
}
public static IServiceCollection AddRepository<TInterface, TImplementation>(this IServiceCollection services)
where TInterface : IRepository
where TImplementation : class, IRepository
{
services.TryAddScoped(typeof(TInterface), typeof(TImplementation));
return services;
}
public static IServiceCollection AddRepository(this IServiceCollection services, Type interfaceType, Type implementationType)
{
services.TryAddScoped(interfaceType, implementationType);
return services;
}
}