If you're using the ABP.IO Framework for your modern .Net applications you may start to use the Local Event Bus. Within the Local Event Bus are Pre-Built events. This article covers how to subscribe to (handle) when an Entity (specifically a user or IdentityUser) has been created.APB.IO provides good documentation on the Local Event Bus - however, the example provided in the "Pre-Built Events" section doesn't work. This article will walk through the steps to handle and respond to the IdentityUser being created.
- Pre-Built Events
- Event Handlers
- Identity (IdentityUser)
- Local Event Bus
- ABP Module and Registration
Pre-Built Events | Creating Your EventHandler
You will need to create a class for your custom event handler.
Create a new Project within your solution and register it as an AbpModule or add your class to an existing project that is all ready registered with your primary module.
using Volo.Abp.DependencyInjection;
using Volo.Abp.Domain.Entities.Events;
using Volo.Abp.EventBus;
using Volo.Abp.Identity;
namespace YourProject.Something.Events;
public class AbpIdentityUserCreationEventHandler
: ILocalEventHandler<EntityCreatedEventData<IdentityUser>>, ITransientDependency
{
private Microsoft.AspNetCore.Identity.UserManager _userManager;
public AbpIdentityUserCreationEventHandler(Microsoft.AspNetCore.Identity.UserManager userManager)
{
_userManager = userManager;
}
public async Task HandleEventAsync( EntityCreatedEventData<IdentityUser> eventData)
{
var userName = eventData.Entity.UserName;
var email = eventData.Entity.Email;
await _userManager.AddToRoleAsync(eventData.Entity, "Business");
}
}
The key difference above is using ABP's IdentityUser vs the one in the namespace Microsoft.AspNetCore.Identity;
Pre-Built Events | Validating Registration (ConfigureServices)
Next we need to verify that the event handler has been registered to the Local Event Bus. We do this by inspecting the handlers.
Within the public override void ConfigureServices(ServiceConfigurationContext context)
method you will need to add the following snipped of code. It relies upon a Logger but you can remove the logger and just set a breakpoint to inspect the count.
If you don't want to verify the count you can inspect the Handlers object and see all the registered handlers. It should include your custom hander.context.Services.Configure(ops => {
_logger.LogInformation(ops.Handlers.Count.ToString());
});
Happy Coding
If you need assistance add a comment.