Я изучаю инъекцию зависимостей и перехват с помощью Castle Windsor и WCF, и я хотел бы проверить, имеет ли перехваченный метод собственный атрибут (LogAttribute).
(Мой пример основан на этом ответе: qaru.site/questions/739029/...)
Контракт на обслуживание:
[ServiceContract]
public interface IOrderService
{
[OperationContract]
Order GetOrder(int orderId);
}
[DataContract]
public class Order
{
[DataMember]
public string Id { get; set; }
// [...]
}
Реализация услуг:
public class OrderService : IOrderService
{
private readonly IDatabase _database;
public OrderService(IDatabase database)
{
_database = database;
}
[Log] // <- my custom attribute
public Order GetOrder(int orderId)
{
return _database.GetOrder(orderId);
}
}
public class LogAttribute : Attribute
{ }
Простой уровень доступа к данным:
public interface IDatabase
{
Order GetOrder(int orderId);
}
public class Database : IDatabase
{
public Order GetOrder(int orderId)
{
return new Order
{
Id = orderId
};
}
}
Инъекция и перехват зависимости:
public class Global : HttpApplication
{
public static WindsorContainer Container { get; private set; }
protected void Application_Start(object sender, EventArgs e)
{
BuildContainer();
}
private static void BuildContainer()
{
if (Container != null)
return;
Container = new WindsorContainer();
Container.AddFacility<WcfFacility>();
Container.Register(Component.For<IInterceptor>().ImplementedBy<MyInterceptor>().LifestyleTransient());
Container.Register(Component.For<IDatabase>().ImplementedBy<Database>().LifestylePerWcfOperation());
Container.Register(Component.For<IStringReverser>().ImplementedBy<StringReverser>().Interceptors<MyInterceptor>());
}
}
public class MyInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
DoSomeWorkBefore(invocation);
invocation.Proceed();
}
private static void DoSomeWorkBefore(IInvocation invocation)
{
if (Attribute.IsDefined(invocation.Method, typeof(LogAttribute)))
{
// This part of the code is never executed
Debug.WriteLine("Method has Log attribute !");
}
}
}
Я уже пробовал invocation.Method.GetCustomAttributes
и Attribute.GetCustomAttribute
, но он не находит LogAttribute. Есть идеи?
служба (Windsor) предназначена для интерфейса IOrderService
и поэтому invocation.Method
укажет на метод на интерфейсе, который не имеет атрибута.
use invocation.MethodInvocationTarget
чтобы получить метод класса