Example: Using a Hook

The following example shows how to implement a hook in a separate CS file (IsEmailAvailableHook.cs).

This example uses a service (see Creating a Service) to learn how to create one) to check if an email is valid.

Then it uses the IsEmailAvailable Hook to check if the email address has been used for another account.

using System;
using DirectScale.Disco.Extension.Hooks;
using DirectScale.Disco.Extension.Hooks.Associates.Enrollment;
using Demo.Services;

namespace Demo.Hooks
{
  public class IsEmailAvailableHook : IHook<IsEmailAvailableHookRequest, IsEmailAvailableHookResponse>
  {
    private readonly IExampleService _exampleService;
    
    public IsEmailAvailableHook(IExampleService exampleService)
    {
      _exampleService = exampleService;
    }
    
    public IsEmailAvailableHookResponse Invoke(IsEmailAvailableHookRequest request, Func<IsEmailAvailableHookRequest, IsEmailAvailableHookResponse> func)
    {
      if (!_exampleService.IsValidEmail(request.EmailAddress))
      {
        return new IsEmailAvailableHookResponse
        {
          IsAvailable = false
          };
      }
      
      return func(request);
    }
  }
}

Next, register the hook in ExtensionEntry.cs.

namespace Demo
{
    public class ExtensionEntry : IExtension
    {
        public void ConfigureServices(IServiceCollection services)
        {
          services.AddTransient<IHook<IsEmailAvailableHookRequest, IsEmailAvailableHookResponse>, IsEmailAvailable>();
        }
    }
}