我有一个场景,我不知道如何最好地使用 Castle 来解决。我正在尝试根据从外部系统检索到的 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;
}
}
有没有人有更好的方法来做到这一点?