Перехват внедрения политики не работает для контроллеров WebAPI

Я реализую внедрение политики с помощью веб-API, а для DI мы используем настраиваемый DependancyResolver. Я использовал подход InterfaceIntercept для реализации внедрения политики. Он отлично работает в случае классов (настраиваемых классов), но внедрение политики не запускается в случае ApiController.

Чтобы вызвать внедрение политики с помощью APIController, я создал интерфейс и реализовал его с помощью контроллера. Общий код ниже: Также мне нужно будет вызвать политику с помощью MessageHandlers.

Код внедрения политики:

public class LogExceptionsCallHandler : ICallHandler
{

    public IMethodReturn Invoke(IMethodInvocation input,
                                GetNextHandlerDelegate getNext)
    {
        IApplicationLogger logger = new ApplicationLogger();
        logger.Log(LoggingLevel.TRACE, "Entering " + input.MethodBase.DeclaringType.FullName + "." + input.MethodBase.Name);
        //// Perform the operation
        var methodReturn = getNext().Invoke(input, getNext);
        //// Method failed, go ahead
        if (methodReturn.Exception != null)
            return methodReturn;
        //// If the result is negative, then throw an exception
        logger.Log(LoggingLevel.TRACE, "Ending " + input.MethodBase.DeclaringType.FullName + "." + input.MethodBase.Name);

        return methodReturn;
    }
    public int Order { get; set; }
}

Код атрибута

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Method)]
public class LogExceptionsAttribute : HandlerAttribute
{
    public LogExceptionsAttribute()
    {
    }
    public HandleLogging HandleLogging { get; set; }
    public int RetryCount { get; set; }
    public override ICallHandler CreateHandler(Microsoft.Practices.Unity.IUnityContainer container)
    {
        return new LogExceptionsCallHandler();
    }
}

Код интерфейса: этот интерфейс реализуется ApiController

[LogExceptions]
public interface IRequestExecutionController : IHttpController
{
    [LogExceptions]
    HttpResponseMessage ExecuteRequest();
}

Интерфейс IRequestExecutionController реализуется RequestExecutionController. Регистрация типа в unity:

container.RegisterType<IDDNPublicAPI.PassThrough.IRequestExecutionController, RequestExecutionController>("requestexecution");

Регистрация перехвата

container.Configure<Interception>().SetInterceptorFor<IDDNPublicAPI.PassThrough.IRequestExecutionController>(new InterfaceInterceptor()); 

Поскольку у нас есть единство для разрешения зависимости, поэтому мы создали класс фабрики контроллера для обработки создания экземпляра контроллера.

public class UnityControllerFactory : IHttpControllerActivator
{
    private IUnityContainer container;

    private readonly IControllerFactory innerFactory;

    public UnityControllerFactory(IUnityContainer container)
        : this(container, new DefaultControllerFactory())
    { }

    public UnityControllerFactory(IUnityContainer container, IControllerFactory innerFactory)
    {`enter code here`
        this.container = container;
        this.innerFactory = innerFactory;
    }enter code here

    public IHttpController Create(HttpRequestMessa`enter code here`ge request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
    {       
        var controller = (IHttpController)this.container.Resolve(controllerType, controllerDescriptor.ControllerName.ToLower());          
        return controller;
    }
} 

И мы зарегистрировали эту фабрику контроллеров в глобальном файле конфигурации. Тот же процесс работает для других классов, но не работает для apicontroller.

Кто-нибудь может что-то предложить по этому поводу?


person ggtffg    schedule 27.02.2014    source источник


Ответы (1)


Контроллеры веб-API не могут быть перехвачены. Но вы можете получить тот же результат, используя фильтр.

Вот хороший пост, показывающий, как вы можете вести журнал в вашем контроллере с помощью фильтров: http://damienbod.wordpress.com/2013/09/15/aop-with-asp-net-web-api/

Вы по-прежнему можете использовать перехватчик ведения журнала для регистрации любого вашего внутреннего кода.

person bayological    schedule 18.06.2014