在下面的单元测试中,我试图注入两个不同组的 MyInterFace[] 数组,但似乎我做错了,因为我将创建所有 IMyInterface 实现的实例,这是相当低效的....
namespace UnitTest.Interface
{
public interface IMyInterface
{
}
}
namespace UnitTest.ArrayGroup1
{
public class MyInjected1 : IMyInterface
{
public static int Instancecount { get; set; }
public MyInjected1()
{
Instancecount++;
}
}
public class MyInjected2 : IMyInterface
{
public static int Instancecount { get; set; }
public MyInjected2()
{
Instancecount++;
}
}
}
namespace UnitTest.ArrayGroup2
{
public class MyInjected3 : IMyInterface
{
public static int Instancecount { get; set; }
public MyInjected3()
{
Instancecount++;
}
}
public class MyInjected4 : IMyInterface
{
public static int Instancecount { get; set; }
public MyInjected4()
{
Instancecount++;
}
}
}
namespace UnitTest
{
public class MyClass1
{
private IMyInterface[] collection;
public MyClass1(IMyInterface[] group1collection)
{
collection = group1collection;
}
}
public class MyClass2
{
private IMyInterface[] collection;
public MyClass2(IMyInterface[] group2collection)
{
collection = group2collection;
}
}
public class MySubResolver : ISubDependencyResolver
{
private readonly IKernel kernel;
public MySubResolver(IKernel kernel)
{
this.kernel = kernel;
}
public bool CanResolve(CreationContext context, ISubDependencyResolver contextHandlerResolver, ComponentModel model, DependencyModel dependency)
{
return dependency.TargetType == typeof(IMyInterface[]);
}
public object Resolve(CreationContext context, ISubDependencyResolver contextHandlerResolver, ComponentModel model, DependencyModel dependency)
{
IMyInterface[] res;
if (dependency.DependencyKey == "group1collection")
res= kernel.ResolveAll<IMyInterface>().Where(t =>
{
var ns = t.GetType().Namespace;
return ns != null && ns.StartsWith("UnitTest.ArrayGroup1");
}).ToArray();
else
res= kernel.ResolveAll<IMyInterface>().Where(t =>
{
var ns = t.GetType().Namespace;
return ns != null && ns.StartsWith("UnitTest.ArrayGroup2");
}).ToArray();
return res;
}
}
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
var kernel = new DefaultKernel(new DefaultProxyFactory());
kernel.Resolver.AddSubResolver(new MySubResolver(kernel));
var container = new WindsorContainer(kernel, new DefaultComponentInstaller());
container.Register(
Classes.FromThisAssembly()
.BasedOn<IMyInterface>()
.WithServiceFirstInterface()
.LifestyleTransient());
container.Register(Component.For<MyClass1>().LifeStyle.Transient);
container.Register(Component.For<MyClass2>().LifeStyle.Transient);
var sut=container.Resolve<MyClass1>();
Assert.AreEqual(MyInjected1.Instancecount, 1);
Assert.AreEqual(MyInjected2.Instancecount, 1);
Assert.AreEqual(MyInjected3.Instancecount, 0);
Assert.AreEqual(MyInjected4.Instancecount, 0);
}
}
}
我如何在我的 SubResolver 中调用 ResolveAll,所以我只得到我真正需要的类的实例?
TIA
/索伦