使用 Unity 解析接口<T>

Resolve Interface<T> with Unity

我在解析映射到 none 通用类型的通用接口时遇到问题。

报名人数:

UnityContainer.RegisterType<IHandle<SomeEvent>, SomeHandler>();
//UnityContainer.RegisterType(typeof(IHandle<SupplierApprovedEvent>), typeof(TestHandler));

这是我尝试解决它但没有成功的方法:

 public static void GenericResolver<T>(T args) where T : IDomainEvent
        {
            var handlerType = typeof(IHandle<>).MakeGenericType(args.GetType());
            var firstTry = container.GetServices(handlerType);// Resolve fails
            var secondTry = container.GetServices(typeof(IHandle<T>)); // Resolve fails

            var casted = args as IDomainEvent;
            var handlerType2 = typeof(IHandle<>).MakeGenericType(casted.GetType());
            var thirdTry = container.GetServices(handlerType2);// Resolve fails

            var handlerType3 = typeof(IHandle<>).MakeGenericType(typeof(T));
            var fourthTry = container.GetServices(handlerType3);// Resolve fails
        }

我的界面:

public interface IDomainEvent {}

public interface IHandle<T>: IHandle where T : IDomainEvent
{
    void Handle(T args);
}

public interface IHandle
{
    void Handle(IDomainEvent args);
}

接口实现:

public class SomeHandler: IHandle<SomeEvent>
{
    public void Handle(IDomainEvent args)
    {
        Handle(args as SomeEvent);
    }

    public void Handle(SomeEvent args)
    {
        //DO SOMETHING
    }
}

我在这里错过了什么:!?

更新:

1.there也不例外。

2.GetService 正在返回 null。

3.This resolve 工作正常,但不是我想要的:

var itsTypeofSomeHangled =(SomeHandler)injector.GetService(typeof(IHandle<SomeEvent>));
例子中的

4.container是继承IDependencyResolver的UnityDependencyResolver。这就是我调用方法 GetServices 和 GerSevice

的原因

更新 2: 原来问题出在GetServices(ResolveAll)。这条线工作得很好,但我有不止一个这个 Gereric 接口的实现。

var handlerType = typeof(IHandle<>).MakeGenericType(args.GetType());
var xxxx = (IHandle)container.GetService(handlerType);

我找到问题所在了。 Unity resolve all 无法按照我在示例中期望的方式工作。 主题中的 Scott Chamberlain 解释涵盖了它。

解决方案:

    var handlerType = typeof(IHandle<>).MakeGenericType(args.GetType());
    var handlers = resolver.Container.Registrations
                       .Where(x => x.RegisteredType.IsGenericType && x.RegisteredType == handlerType)
                       .Select(x => (IHandle)resolver.GetService(x.RegisteredType));

    foreach (IHandle item in handlers)
    {
        item.Handle(args);
    }

基本上我在这里所做的是查询容器注册以查找我的处理程序类型。比起在 .Select 中,我使用特定的 registration.RegisteredType 参数调用 GetService(Resolve) 并且当然会对其进行转换。比在 foreach 中更明显...