【发布时间】:2014-02-02 13:04:05
【问题描述】:
示例类
public interface IDog
{
string Bark();
}
public interface ICat
{
string Meow();
}
public class DogCat : IDog, ICat
{
public string Bark()
{
return "Bark";
}
public string Meow()
{
return "Meow";
}
}
在没有拦截器的世界里,如果我有实例,我可以轻松地施放它。
IDog dog = new DogCat();
ICat cat = (Cat)dog;
这是测试。如果我不使用LoggingInterceptor,我会参考DogCat,而cast 会起作用。
但是当我使用接口时,它不能转换。测试通过,即抛出InvalidCastException。我怎样才能让它不投掷?我可以得到一个可以用作ICat的代理吗?
[TestFixture]
public class LoggingInterceptorTests2
{
private WindsorContainer _container;
private Mock<ILogger> _mock;
[SetUp]
public void SetUp()
{
_container = new WindsorContainer();
_mock = new Mock<ILogger>(MockBehavior.Loose);
_container.Register(
Component.For<LoggingInterceptor>().LifestyleTransient().DependsOn(new { HeavyLogging = true }),
Component.For<IDog>().ImplementedBy<DogCat>().Named("dog").Interceptors<LoggingInterceptor>(),
Component.For<ICat>().ImplementedBy<DogCat>().Named("cat").Interceptors<LoggingInterceptor>()
);
}
[Test]
public void CastInterceptorForATypeImplementing2Interfaces()
{
var dog = _container.Resolve<IDog>();
dog.Bark().Should().Be("Bark");
Action cat = () =>
{
var t = (ICat)dog;//I want it to be casted here
};
cat.ShouldThrow<InvalidCastException>();
}
}
任务是我有一组服务执行任务,在某些情况下可能是扩展服务。我打算投射到扩展,如果投射成功,我会进行扩展操作。一切都很好,但我需要将它用作 Wcf 并使用拦截器。我该怎么做?
【问题讨论】:
-
你为什么要以狗的名义投那个?你需要投射的事实对我来说似乎是有缺陷的。为什么不同时注入
IDog和ICat? -
我无法注入 IDog 和 ICat。事实上,我正在使用集合解析器注入 IEnumerable
。如果我注入 IEnumerable ,假设是 IEnumerable 大小的一半。我无法为 IDog 找出可选的 ICat。 -
使用混合。此处选择的答案 (stackoverflow.com/questions/678131/windsor-mixin-is-a-singleton) 给出了一个示例,尽管它使用的是 VB 而不是 C#。
标签: casting castle-windsor interceptor castle-dynamicproxy