В настоящее время я создаю образец приложения с использованием Castle Windsor. Девиз - использовать xml / app.config для включения / выключения перехвата методов. Раньше я использовал Fluent API, и он работал как прелесть. В качестве следующего шага я пытаюсь заменить свободный API своим xml.
Суть кода такова: класс с именем RandomOperations с двумя виртуальными методами. Класс LoggingAspect, реализующий IInterceptor. Класс MyInterceptorsSelector, который реализует IModelInterceptorsSelector A Program.cs, который раньше имел свободный синтаксис api и теперь используется только для вызовов методов класса RandomOperations. App.config с вызываемым разделом, который имеет синтаксис xml для регистрации компонентов.
Когда я использую свободный API, я могу перехватывать вызовы методов, но не могу сделать это с помощью регистрации xml / app.config. Может кто-нибудь пролить свет на то, что упускается?
Классы следующие:
RandomOperations.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");
}
Удаление закомментированного синтаксиса свободного API позволяет приложению работать правильно.
App.config
<?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>
Заранее спасибо.