キャッスルとの最善の解決方法がわからないというシナリオがあります。外部システムから取得した ID に基づいて型を解決しようとしています。注意が必要なのは、複数の ID が同じ具象型に関連付けられていることです。
これが私がこれまでに思いついたものです。これは少し間違っているように感じます。ResolveAll を呼び出す必要があるという事実は気に入らない。
[TestFixture]
public class TestWindsor
{
[Test]
public void AddGreenResolverToContainer_ShouldResolveCorrectTypeAndTypeId()
{
//---------------Set up test pack-------------------
IWindsorContainer container = new WindsorContainer();
//---------------Assert Precondition----------------
//---------------Execute Test ----------------------
container.Register(Component.For<IResolver>()
.ImplementedBy<TestOneResolver>()
.DependsOn(new {typeId = "1"}));
//---------------Test Result -----------------------
var actual = container.Resolve<IResolver>();
Assert.IsInstanceOf<TestOneResolver>(actual);
Assert.AreEqual("1", actual.typeId);
}
[Test]
public void AddTwoNamedGreenResolverToContainer_ShouldResolveTwoTypes()
{
//---------------Set up test pack-------------------
IWindsorContainer container = new WindsorContainer();
//---------------Assert Precondition----------------
//---------------Execute Test ----------------------
container.Register(Component.For<IResolver>()
.ImplementedBy<TestOneResolver>()
.DependsOn(new {typeId = "1"}).Named("tageventstatusresolver"));
container.Register(Component.For<IResolver>()
.ImplementedBy<TestOneResolver>()
.DependsOn(new {typeId = "2"}).Named("second"));
container.Register(Component.For<IResolver>()
.ImplementedBy<TestTwoResolver>()
.DependsOn(new {typeId = "1122"}).Named("redFirst"));
container.Register(Component.For<IResolverFactory>()
.ImplementedBy<ResolverFactory>()
.DependsOn(new { resolvers=container.ResolveAll<IResolver>()}));
//---------------Test Result -----------------------
var actual = container.Resolve<IResolverFactory>();
var resolver = actual.Create("1");
Assert.IsInstanceOf<TestOneResolver>(resolver);
}
}
public interface IResolverFactory
{
IResolver Create(string typeId);
}
public class ResolverFactory : IResolverFactory
{
private readonly IResolver[] _resolvers;
public ResolverFactory(IResolver[] resolvers)
{
_resolvers = resolvers;
}
public IResolver Create(string typeId)
{
return _resolvers.Where(resolver => resolver.typeId == typeId).FirstOrDefault();
}
}
public enum ResolutionStatus
{
Red,
Green,
Amber
}
public interface IResolver
{
string typeId { get; }
ResolutionStatus Resolve();
}
public class TestOneResolver : IResolver
{
public TestOneResolver(string typeId)
{
this.TypeId = typeId;
}
public string TypeId { get; private set; }
public ResolutionStatus Resolve()
{
return ResolutionStatus.Green;
}
}
public class TestTwoResolver : IResolver
{
public TestTwoResolver(string typeId)
{
TypeId = typeId;
}
public string TypeId { get; private set; }
public ResolutionStatus Resolve()
{
return ResolutionStatus.Red;
}
}
これを行うためのより良い方法について誰か提案がありますか?