我的当前注册码:
Assembly web = Assembly.Load("MyAssembly");
types.AddRange(web.GetTypes());
//etc.
foreach (var theInterface in types.Where(t => t.IsInterface))
{
var assignableType = types.Where(t => theInterface.IsAssignableFrom(t) && t != theInterface);
foreach (var type in assignableType)
{
container.RegisterType(theInterface, type);
}
}
我的通用接口及其实现:
public interface IDomainEventHandler<in T>
{
void Handle(T message);
}
public class DomainEventHandler1 : IDomainEventHandler<PhilTest1>
{
public void Handle(PhilTest1 message)
{
throw new System.NotImplementedException();
}
}
public class DomainEventHandler2 : IDomainEventHandler<PhilTest2>
{
public void Handle(PhilTest2 message)
{
throw new System.NotImplementedException();
}
}
public class DomainEventHandler3 : IDomainEventHandler<PhilTest2>
{
public void Handle(PhilTest2 message)
{
throw new System.NotImplementedException();
}
}
public class PhilTest1
{
}
public class PhilTest2
{
}
以下是我解决问题的简化版本:
IEnumerable<IDomainEventHandler<PhilTest2>> listeners = Container.ResolveAll<IDomainEventHandler<PhilTest2>>();
IEnumerable<IDomainEventHandler<PhilTest1>> listeners2 = Container.ResolveAll<IDomainEventHandler<PhilTest1>>();
这段代码无法实现 - 当解决后,listeners和listeners2都为空。这是预料中的结果。
在Windsor中,我可以这样做:
container.Register(AllTypes.FromAssemblyNamed("MyAssembly").BasedOn(typeof(IDomainEventHandler<>)).WithService.Base());
我该如何在Unity中注册所有IDomainEventHandler实例?如果可能的话,我希望保留现有的注册代码不变。
container.RegisterTypes
方法实现了基于约定的注册。而且这个方法还支持泛型!太棒了! - MichaC