0

我需要注册多个具有相同接口但因任何字符串约束而不同的服务。更具体地说:

[EventName("Domain/Task/Actions/Save")]
public class EntitySavedEventReceiver1 : IEventReceiver
{
    public void Receive(RemoteEvent evnt)
    {
    }
}

[EventName("Domain/Task/Actions/Save")]
public class EntitySavedEventReceiver2 : IEventReceiver
{
    public void Receive(RemoteEvent evnt)
    {
    }
}

我试过的注册:

foreach (Type eventReceiverType in mainAssembly.GetTypes().Where(x => typeof (IEventReceiver).IsAssignableFrom(x)))
{
    var attributes = eventReceiverType.GetCustomAttributes(typeof (EventNameAttribute), false);

    foreach (var attribute in attributes.Cast<EventNameAttribute>())
    {
        builder.RegisterType(eventReceiverType)
            .Keyed<IEventReceiver>(attribute.EventName)
            // tried also named
            .AsImplementedInterfaces();
    }
}

并解析函数:

builder.Register<Func<string, IEnumerable<IEventReceiver>>>(c =>
    {
        var ctx = c.Resolve<IComponentContext>();
        return eventName =>
            {
                var eventReceiver = ctx.ResolveKeyed<IEventReceiver>(eventName);
                return new [] { eventReceiver };
            };
    });

这很完美,但我需要在相同的名称或密钥上注册多个服务,并且能够解决所有问题。

4

1 回答 1

2

利用

ctx.ResolveKeyed<IEnumerable<IEventReceiver>>(eventName)

请参阅关系类型以供参考。

于 2013-07-15T13:29:38.883 回答