-
Notifications
You must be signed in to change notification settings - Fork 315
/
MultitenancyServiceCollectionExtensions.cs
40 lines (32 loc) · 1.55 KB
/
MultitenancyServiceCollectionExtensions.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
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection.Extensions;
using SaasKit.Multitenancy;
using System.Reflection;
namespace Microsoft.Extensions.DependencyInjection
{
using SaasKit.Multitenancy.Internal;
public static class MultitenancyServiceCollectionExtensions
{
public static IServiceCollection AddMultitenancy<TTenant, TResolver>(this IServiceCollection services)
where TResolver : class, ITenantResolver<TTenant>
where TTenant : class
{
Ensure.Argument.NotNull(services, nameof(services));
services.AddScoped<ITenantResolver<TTenant>, TResolver>();
// No longer registered by default as of ASP.NET Core RC2
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
// Make Tenant and TenantContext injectable
services.AddScoped(prov => prov.GetService<IHttpContextAccessor>()?.HttpContext?.GetTenantContext<TTenant>());
services.AddScoped(prov => prov.GetService<TenantContext<TTenant>>()?.Tenant);
// Make ITenant injectable for handling null injection, similar to IOptions
services.AddScoped<ITenant<TTenant>>(prov => new Tenant<TTenant>(prov.GetService<TTenant>()));
// Ensure caching is available for caching resolvers
var resolverType = typeof(TResolver);
if (typeof(MemoryCacheTenantResolver<TTenant>).IsAssignableFrom(resolverType))
{
services.AddMemoryCache();
}
return services;
}
}
}