我有多个通知,我需要为IBusEvent类型的所有通知只有一个处理程序实例。
这是我目前的情况
通知
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
}
IOC
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只有一个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,有没有更好的方法来实现这一目标?