【问题标题】:Cast of the intercepted(Castle Windsor interceptor) interface to another interface将拦截的(Castle Windsor 拦截器)接口转换为另一个接口
【发布时间】: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


【解决方案1】:

尝试更改为:

Component.For<IDog,DogCat>().ImplementedBy<DogCat>().Named("dog").Interceptors<LoggingInterceptor>(),
Component.For<ICat,DogCat>().ImplementedBy<DogCat>().Named("cat").Interceptors<LoggingInterceptor>()

这应该会强制 Windsor 使用类代理。不过,我确实同意上面的评论,即您的设计似乎有缺陷。好久没用了,如果不行请告诉我,我再查一下。

亲切的问候, 马尔维恩

【讨论】:

  • 我已经更改了设计,但仍然非常感谢。有用。这正是我要找的。​​span>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-26
  • 2012-06-01
相关资源
最近更新 更多