xonery
xonery
CC#
Created by xonery on 2/14/2023 in #help
❔ Generics
Hi, I commented the code to explain my issue
public async Task DispatchAsync(IEventContext context)
{
var @event = _dictionary.Resolve<IEvent<TAggregateIdentifier>, TAggregateIdentifier>(context.Identifier, context.Payload);

// 1. So far
// @event.GetType() -> MyEvent

await _domain.HandleDomainAsync(@event);
}

public async Task HandleDomainAsync<TEvent>(TEvent @event) where TEvent : IEvent<TAggregateIdentifier>
{
// 2. So far
// typeof(TEvent) -> IEvent<TAggregateIdentifier>
// @event.GetType() -> MyEvent

// 3. I have to use MakeGenericType to retrieve a list of IDomainEventHandler<TAggregateRoot, TAggregateIdentifier, MyEvent>
// as i cannot use TEvent directly.

var type = typeof(IDomainEventHandler<,,>).MakeGenericType(typeof(TAggregateRoot), typeof(TAggregateIdentifier),
@event.GetType());

var service = _services.GetService(type);

// 4. As GetService returned an object, I have to cast to IDomainEventHandler<TAggregateRoot, TAggregateIdentifier, TEvent>
// so i can call service.HandleAsync(@event)

// 5. This doesn't work tho, as typeof(TEvent) -> IEvent<TAggregateIdentifier>, witch makes sence
if(service is IDomainEventHandler<TAggregateRoot, TAggregateIdentifier, TEvent> handler)
await handler.HandleAsync(@event);

// Question: I there any way I can make it working without using reflection to invoke HandleAsync ?
//
}
public async Task DispatchAsync(IEventContext context)
{
var @event = _dictionary.Resolve<IEvent<TAggregateIdentifier>, TAggregateIdentifier>(context.Identifier, context.Payload);

// 1. So far
// @event.GetType() -> MyEvent

await _domain.HandleDomainAsync(@event);
}

public async Task HandleDomainAsync<TEvent>(TEvent @event) where TEvent : IEvent<TAggregateIdentifier>
{
// 2. So far
// typeof(TEvent) -> IEvent<TAggregateIdentifier>
// @event.GetType() -> MyEvent

// 3. I have to use MakeGenericType to retrieve a list of IDomainEventHandler<TAggregateRoot, TAggregateIdentifier, MyEvent>
// as i cannot use TEvent directly.

var type = typeof(IDomainEventHandler<,,>).MakeGenericType(typeof(TAggregateRoot), typeof(TAggregateIdentifier),
@event.GetType());

var service = _services.GetService(type);

// 4. As GetService returned an object, I have to cast to IDomainEventHandler<TAggregateRoot, TAggregateIdentifier, TEvent>
// so i can call service.HandleAsync(@event)

// 5. This doesn't work tho, as typeof(TEvent) -> IEvent<TAggregateIdentifier>, witch makes sence
if(service is IDomainEventHandler<TAggregateRoot, TAggregateIdentifier, TEvent> handler)
await handler.HandleAsync(@event);

// Question: I there any way I can make it working without using reflection to invoke HandleAsync ?
//
}
6 replies