2
解决映射到非泛型类型的通用接口问题。使用Unity解析接口<T>
报名:
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
}
}
我在这里想念什么:!?
UPDATE:
1.有没有例外。
2.GetService返回null。
3,本解决工作正常,但它不是我想要的东西:
var itsTypeofSomeHangled =(SomeHandler)injector.GetService(typeof(IHandle<SomeEvent>));
4.container的例子是UnityDependencyResolver它继承的IDependencyResolver。这就是为什么我调用方法GetServices和GerSevice
UPDATE2的原因: 原来,问题出在GetService的小号(ResolveAll)。这条线完美地工作,但我有不止一个这个Gereric接口的实现。
var handlerType = typeof(IHandle<>).MakeGenericType(args.GetType());
var xxxx = (IHandle)container.GetService(handlerType);
GetServices是你自己创建的扩展方法吗?或者你的意思是使用'Resolve'来代替? –
为什么你调用'container.GetServices'而不是'container.Resolve'? – Steven
容器是UnityDependencyResolver作为IDependencyResolver公开的。这就是为什么它的GetService而不是Resolve – IIvanov