|
| 1 | +using Microsoft.Extensions.DependencyInjection; |
| 2 | +using SenseNet.Client; |
| 3 | +using SenseNet.Client.WebApi; |
| 4 | + |
| 5 | +// ReSharper disable once CheckNamespace |
| 6 | +namespace SenseNet.Extensions.DependencyInjection |
| 7 | +{ |
| 8 | + public static class RepositoryExtensions |
| 9 | + { |
| 10 | + /// <summary> |
| 11 | + /// Adds sensenet client services and registers three repositories: User, Visitor and Admin. |
| 12 | + /// All repositories are configured with the same options, the only difference is the authentication. <br/><br/> |
| 13 | + /// - the <b>Visitor</b> repository will not have any<br/> |
| 14 | + /// - the <b>Admin</b> repository will use the configured Admin user<br/> |
| 15 | + /// - the <b>User</b> repository will try to authenticate using the current user's token available in HttpContext<br/> |
| 16 | + /// <br/> |
| 17 | + /// To make advantage of these repositories, use the <see cref="IUserRepositoryCollection"/> service |
| 18 | + /// in your classes. |
| 19 | + /// </summary> |
| 20 | + /// <param name="services"></param> |
| 21 | + /// <param name="configure">Callback for configuring <see cref="RepositoryOptions"/> instance.</param> |
| 22 | + /// <param name="registerContentTypes">Optional callback for registering custom content types.</param> |
| 23 | + public static IServiceCollection AddSenseNetClientWithUserRepositories(this IServiceCollection services, |
| 24 | + Action<RepositoryOptions> configure, Action<RegisteredContentTypes>? registerContentTypes = null) |
| 25 | + { |
| 26 | + services.AddHttpContextAccessor(); |
| 27 | + services.AddSenseNetClient(); |
| 28 | + |
| 29 | + services.ConfigureSenseNetRepository(Repositories.VisitorRepository, |
| 30 | + ConfigureWithEmptyAuthentication(configure), |
| 31 | + registerContentTypes) |
| 32 | + .ConfigureSenseNetRepository(Repositories.UserRepository, |
| 33 | + ConfigureWithEmptyAuthentication(configure), |
| 34 | + registerContentTypes) |
| 35 | + .ConfigureSenseNetRepository(Repositories.AdminRepository, |
| 36 | + configure, |
| 37 | + registerContentTypes); |
| 38 | + |
| 39 | + // this can be singleton, because it requires only singleton services like IHttpContextAccessor |
| 40 | + services.AddSingleton<IUserRepositoryCollection, UserRepositoryCollection>(); |
| 41 | + |
| 42 | + return services; |
| 43 | + } |
| 44 | + |
| 45 | + private static Action<RepositoryOptions> ConfigureWithEmptyAuthentication(Action<RepositoryOptions>? configure) |
| 46 | + { |
| 47 | + return options => |
| 48 | + { |
| 49 | + configure?.Invoke(options); |
| 50 | + |
| 51 | + // clear all auth data to prevent accidental use of client credentials |
| 52 | + options.Authentication.ClientId = string.Empty; |
| 53 | + options.Authentication.ClientSecret = string.Empty; |
| 54 | + options.Authentication.ApiKey = string.Empty; |
| 55 | + }; |
| 56 | + } |
| 57 | + } |
| 58 | +} |
0 commit comments