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