我目前正在使用 Castle Windsor 构建一个示例应用程序。座右铭是使用 xml/app.config 来打开/关闭方法拦截。我之前使用过 Fluent API,它很有魅力。作为下一步,我正在尝试用我的 xml 替换 fluent API。
代码的要点如下: 一个名为 RandomOperations 的类,具有两个虚拟方法。实现 IInterceptor 的 LoggingAspect 类。实现 IModelInterceptorsSelector 的 MyInterceptorsSelector 类 Program.cs 之前具有流畅的 api 语法,现在仅用于调用 RandomOperations 类的方法。一个 app.config 带有一个名为的部分,该部分具有注册组件的 xml 语法。
当我使用流利的 api 时,我能够拦截方法调用,但我无法使用 xml/app.config 注册。有人可以说明一下错过了什么吗?
课程如下:
随机操作.cs
public class RandomOperations
{
public virtual int MyRandomMethod(int x)
{
return x * x;
}
public virtual void Writer(string x)
{
Console.WriteLine(x);
}
}
LoggingAspect.cs
public class LoggingAspect : IInterceptor
{
public void Intercept(IInvocation invocation)
{
Console.WriteLine("Intercepted the call to " + invocation.Method.Name);
invocation.Proceed();
Console.WriteLine("After the method call, the return value is " + invocation.ReturnValue);
}
}
MyInterceptorsSelector.cs
public class MyInterceptorsSelector : IModelInterceptorsSelector
{
public bool HasInterceptors(ComponentModel model)
{
return typeof(LoggingAspect) != model.Implementation &&
model.Implementation.Namespace.StartsWith("ConsoleApplication1") ;
}
public InterceptorReference[] SelectInterceptors(ComponentModel model, Castle.Core.InterceptorReference[] obj)
{
var interceptors = new List<InterceptorReference>(model.Interceptors.Count + 1);
foreach (InterceptorReference inter in model.Interceptors)
{
interceptors.Add(inter);
}
return interceptors.ToArray();
}
}
主要在 Program.cs
static void Main(string[] args)
{
var container = new WindsorContainer();
//container.Register(Component.For<RandomOperations>().Interceptors(typeof(LoggingAspect)));
//container.Register(Component.For<LoggingAspect>());
//container.Kernel.ProxyFactory.AddInterceptorSelector(new MyInterceptorsSelector());
var service = container.Resolve<RandomOperations>();
service.MyRandomMethod(4);
service.Writer("Hello, World");
}
删除注释掉的 fluent api 语法使应用程序正常工作。
应用程序配置
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="castle" type="Castle.Windsor.Configuration.AppDomain.CastleSectionHandler, Castle.Windsor" />
</configSections>
<castle>
<components>
<component id="MyInterceptorsSelector" type="MyInterceptorsSelector"/>
<component
id="LoggingAspect"
type="ConsoleApplication1.LoggingAspect, ConsoleApplication1">
</component>
<component
type="ConsoleApplication1.RandomOperations, ConsoleApplication1">
<interceptors selector="${MyInterceptorsSelector}">
<interceptor>${LoggingAspect}</interceptor>
</interceptors>
</component>
</components>
</castle>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
提前致谢。