Reputation: 1178
Tested with: Automapper 10.1.2-alpha.0.4 (MyGet Build)
We want to map our DomainEvents to public Contracts that do not have any base classes and publish them to a Message Queue/Topic.
As it should be a dynamic mapping, we do not know the target type while the mapping to the destination contract occurs.
For that case, we had the following solution of this Post: How can I use Automapper to map an object to an unknown destination type? as follows:
public async Task Publish(DomainEvent domainEvent)
{
this.logger.LogInformation("Publishing domain event. Event - {event}", domainEvent.GetType().Name);
try
{
var publicEvent = this.MapToContract(domainEvent);
await this.publishEndpoint.Publish(publicEvent);
}
catch (Exception ex)
{
this.logger.LogError("Unexpected exception while publishing domain event.", ex);
}
}
private object MapToContract(object source)
{
var sourceType = source.GetType();
TypeMap? typeMap = null;
try
{
typeMap = this.mapper.ConfigurationProvider
.GetAllTypeMaps()
.SingleOrDefault(map => map.SourceType == sourceType);
}
catch (InvalidOperationException)
{
throw new Exception($"Multiple types for {sourceType.FullName} available. Only one allowed");
}
return typeMap is null
? throw new Exception($"No type map for {sourceType.FullName} found!")
: this.mapper.Map(source, sourceType, typeMap.DestinationType);
}
Publish(DomainEvent domainEvent)
gets called as event receiver whenever an domain event is raised.
Since the last version, we can't use the MapToContract
method anymore because the GetAllTypeMaps
method is not available. I was not able to find any workaround.
Sample of the public event class:
public record EmployeeCreated(int Id, string Name, string FirstName);
Any ideas?
Upvotes: 2
Views: 2054
Reputation: 156
Ok, had the same problem. Solution is to use the internal extension method as follows (see https://docs.automapper.org/en/stable/11.0-Upgrade-Guide.html?highlight=internal#forallmaps-forallpropertymaps-advanced-and-other-missing-apis):
using AutoMapper.Internal;
...
this.mapper.ConfigurationProvider
.Internal()
.GetAllTypeMaps()
...
Upvotes: 14