Example classes
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";
}
}
In the world without interceptors if I have instance I can cast it easily.
IDog dog = new DogCat();
ICat cat = (Cat)dog;
Here's the test. If I don't use LoggingInterceptor
, I would get reference to a DogCat
and cast
will work.
But as I use interface it can't cast. The test passes, i.e. throws InvalidCastException
. How can I make it do not throw and cast it? Can I get a proxy which can be used as 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>();
}
}
The task is I have a banch of services performing tasks and in some cases in may be extended services. I was going to cast to extended and if the cast is successful I do extended operations. All is fine but I need to use it as Wcf & use interceptors. How can I do that?
try changing to :
Component.For<IDog,DogCat>().ImplementedBy<DogCat>().Named("dog").Interceptors<LoggingInterceptor>(),
Component.For<ICat,DogCat>().ImplementedBy<DogCat>().Named("cat").Interceptors<LoggingInterceptor>()
This should force windsor to use a class proxy. I do agree however with the comment above that your design seems to be flawed. It's been a while since I've used this, so let me know if it doesn't work, then I'll look it up.
Kind Regards, Marwijn