我在运行时解析通用接口实现时遇到问题。我正在使用一个事件总线,它将根据事件的类型解析事件处理程序。当我尝试在没有通用实现的情况下解决事件处理程序时,一切都会按预期进行。我想实现一个通用接口,这样我就可以有一个处理特定类型事件的基类。
在创建通用实现之前,我遇到过以下情况:
public interface IEvent
{
Guid EntityId { get; set; }
}
public interface IEventHandler<TEvent> where TEvent : IEvent
{
Task Handle(TEvent @event);
}
public class EventBus
{
private readonly IComponentContext _context;
public EventBus(IComponentContext context)
{
_context = context;
}
public async Task HandleEvent<TEvent>(TEvent @event) where TEvent : IEvent
{
var handler = _context.Resolve<IEventHandler<TEvent>>();
await handler.Handle(@event);
}
}
我按如下方式注册事件处理程序:
builder.RegisterAssemblyTypes(ThisAssembly).AsClosedTypesOf(typeof(IEventHandler<>));
实施示例:
public class FooEventHandler :
IEventHandler<FooArchivedEvent>,
IEventHandler<FooRestoredEvent>,
IEventHandler<FooSomethingElseHappenedEvent>
{
private readonly IRepository<Foo> _repository;
public FooEventHandler(IRepository<Foo> repository)
{
_repository = repository;
}
public async Task Handle(FooArchivedEvent @event)
{
var Foo = await _repository.Get(@event.EntityId);
Foo.Archive();
}
public async Task Handle(FooRestoredEvent @event)
{
var Foo = await _repository.Get(@event.EntityId);
Foo.Restore();
}
public async Task Handle(FooSomethingElseHappenedEvent @event)
{
// do something else with Foo
}
}
宝慕林4294392