我无法弄清楚正确的使用方法RegisterAllOpenGeneric
我有这些简单的定义:
public interface ISubscribeTo<T> { }
public class AnEventOf<T> { }
public interface IMarker { }
public class PocoB : IMarker { }
和一个正常 Subscriber
的:
public class SubscribeToPocoB : ISubscribeTo<AnEventOf<PocoB>>
{
}
使用以下代码注册:
private void RegisterSubscribers(Container container)
{
var implementations = new List<Type>();
container.RegisterManyForOpenGeneric(typeof(ISubscribeTo<>),
AccessibilityOption.PublicTypesOnly,
(serviceType, implTypes) =>
{
container.RegisterAll(serviceType, implTypes);
implementations.AddRange(implTypes);
},
AppDomain.CurrentDomain.GetAssemblies()
);
implementations
.Distinct()
.ToList()
.ForEach(type => container.Register(type));
container.Verify();
}
并在调用时返回:
var registrations = container
.GetAllInstances<ISubscribeTo<AnEventOf<PocoB>>>();
到目前为止一切都很好。
PocoB
还实现了接口IMarker
,我正在尝试创建一个Subscriber
在AnEventOf<IMarker>>
调用GetAllInstances<ISubscribeTo<AnEventOf<PocoB>>>();
.
我尝试了 3 种不同的定义:
public class SubscribeToIMarker1<TMarker> : ISubscribeTo<AnEventOf<TMarker>>
where TMarker : IMarker
{
}
public class SubscribeToIMarker2<TAnEventOf> : ISubscribeTo<TAnEventOf>
where TAnEventOf : AnEventOf<IMarker>
{
}
public class SubscribeToIMarker3<TMarker> : ISubscribeTo<TMarker>
where TMarker : IMarker
{
}
这是我编写的不同测试方法 - 没有一个测试有效,它们都只返回SubscribeToPocoB
:
[Test]
public void GetAllInstances_PocoB1_ReturnTwoRegistrations()
{
Container container = new Container();
container.RegisterAllOpenGeneric(
typeof(ISubscribeTo<>),
typeof(SubscribeToIMarker1<>));
RegisterSubscribers(container);
var registrations = container
.GetAllInstances<ISubscribeTo<AnEventOf<PocoB>>>();
Assert
.That(registrations.Count(),
Is.EqualTo(2));
}
[Test]
public void GetAllInstances_PocoB2_ReturnTwoRegistrations()
{
Container container = new Container();
container.RegisterAllOpenGeneric(
typeof(ISubscribeTo<>),
typeof(SubscribeToIMarker2<>));
RegisterSubscribers(container);
var registrations = container
.GetAllInstances<ISubscribeTo<AnEventOf<PocoB>>>();
Assert
.That(registrations.Count(),
Is.EqualTo(2));
}
[Test]
public void GetAllInstances_PocoB3_ReturnTwoRegistrations()
{
Container container = new Container();
container.RegisterAllOpenGeneric(
typeof(ISubscribeTo<>),
typeof(SubscribeToIMarker3<>));
RegisterSubscribers(container);
var registrations = container
.GetAllInstances<ISubscribeTo<AnEventOf<PocoB>>>();
Assert
.That(registrations.Count(),
Is.EqualTo(2));
}
我是否需要做更多的事情才能正确注册所有开放的泛型(例如SubscribeToIMarker1
)?
container.RegisterAllOpenGeneric(
typeof(ISubscribeTo<>),
typeof(SubscribeToIMarker1<>));