2

我有多个通知,对于所有 IBusEvent 类型的通知,我只需要 1 个处理程序实例。

这是我目前的情况

通知

public interface IBusEvent : IAsyncNotification
{
}

public class RecEnded : IBusEvent
{
    public long RecId { get; set; }

    public RecEnded(long recId)
    {
        RecId = recId;
    }
}

public class RecStarted : IBusEvent
{
    public long RecId { get; set; }
    public int InitiatorCellId { get; set; }

    public RecStarted(long recId, int initiatorCellId)
    {
        RecId = recId;
        InitiatorCellId = initiatorCellId;
    }
}

处理程序

对于这两个通知,我只有一个处理程序。

public class BusEventHandler : IAsyncNotificationHandler<IBusEvent>, IDisposable
{
    private IBusConfig _config;

    public BusEventHandler(IBusConfig config)
    {
        _config = config;
        // connect to the bus
    }

    public async Task Handle(IBusEvent notification)
    {
         // send package to the bus
    }

    public void Dispose()
    {
         // close & dispose connection
    }

国际奥委会

public class MediatorRegistry : Registry
{
    public MediatorRegistry()
    {
        For<SingleInstanceFactory>().Use<SingleInstanceFactory>(ctx => t => ctx.GetInstance(t));
        For<MultiInstanceFactory>().Use<MultiInstanceFactory>(ctx => t => ctx.GetAllInstances(t));
        For<IMediator>().Use<Mediator>();
    }
}

public class HandlersRegistry : Registry
{
    public HandlersRegistry()
    {
        // I have multiple configs for IBusConfig.
        // get the configuration from the config file
        List<IBusConfig> configs = AppSettings.GetBusConfigs();
        foreach (IBusConfig config in configs)
             For(typeof(IAsyncNotificationHandler<IBusEvent>))
                 .Singleton()
                 .Add(i => new BusEventHandler(config));
    }

}

我需要的

通过这个 IOC 注册表,我为每个 IBusConfig 接收到 2 个 BusEventHandler 实例。

对于每个 IBusConfig,我只需要 1 个 BusEventHandler 实例。

我可以实现良好行为的唯一方法是更改​​ MediatorRegistry

public class MediatorRegisty : Registry
{
    public MediatorRegisty()
    {
        For<SingleInstanceFactory>().Use<SingleInstanceFactory>(ctx => t => ctx.GetInstance(t));
        For<MultiInstanceFactory>().Use<MultiInstanceFactory>(ctx => t => TryGetAllInstances(ctx, t));
        For<IMediator>().Use<Mediator>();
    }

    private static IEnumerable<object> TryGetAllInstances(IContext ctx, Type t)
    {
        if (t.GenericTypeArguments[0].GetInterfaces().Contains(typeof(IBusEvent)))
            return ctx.GetAllInstances(typeof(IAsyncNotificationHandler<IBusEvent>));
        else
            return ctx.GetAllInstances(t);
    }
}

在不更改 MediatorRegistry 的情况下有没有更好的方法来实现这一点?

4

0 回答 0