К какому объекту HttpConfiguration мне нужен доступ для создания пользовательского HttpParameterBinding?

В этом посте Майк Уоссон заявляет:

"Помимо ParameterBindingAttribute, есть еще один хук для добавления пользовательского HttpParameterBinding. В объекте HttpConfiguration"

Но у меня есть три объекта HttpConfiguration в моем приложении Web API, а именно:

public static void Register(HttpConfiguration config, IWindsorContainer container) <-- in WebApiConfig.cs
private static void MapRoutes(HttpConfiguration config) <-- ""
public static void ConfigureWindsor(HttpConfiguration configuration) <-- in Global.asax.cs

Какой из них (конфиг, конфиг или конфигурация) мне следует использовать (если есть)?

ОБНОВИТЬ

Я попробовал это с точкой останова на строке "если":

public static void ConfigureWindsor(HttpConfiguration configuration)
{
    _container = new WindsorContainer();
    _container.Install(FromAssembly.This());
    _container.Kernel.Resolver.AddSubResolver(new CollectionResolver(_container.Kernel, true));
    var dependencyResolver = new WindsorDependencyResolver(_container);
    configuration.DependencyResolver = dependencyResolver;

    if (configuration.Properties.Values.Count > 0) // <-- I put a Casey Jones here
    {
        object o = configuration.Properties.Values.ElementAt(configuration.Properties.Values.Count - 1);
        string s = o.ToString();
    }
}

... но я попал в эту точку только один раз, при запуске сервера, но не когда клиент отправил ему запрос... должно быть какое-то событие, которое запускается, когда сервер передает запрос, где может быть входящий URL рассмотрел... нет?

1 ответ

Решение

Обычно у вас есть только один экземпляр HttpConfiguration, который вы получаете из GlobalConfiguration.Configuration.

Сказал так, вот как я подключил пользовательские связующие

В глобальном.asax

var binderMappings = new Dictionary<Type, Type>
    {
        {typeof(YourModelType), typeof(YourModelTypeBinder)},
        //....
    };

config.Services.Add(
    typeof(ModelBinderProvider),
    new WindsorModelBinderProvider(container, binderMappings));

WindsorModelBinderProvider

public class WindsorModelBinderProvider : ModelBinderProvider
{
    private readonly IWindsorContainer _container;
    private readonly IDictionary<Type, Type> _binderMappings;

    public WindsorModelBinderProvider(IWindsorContainer container, IDictionary<Type, Type> binderMappings)
    {
        _container = container;
        _binderMappings = binderMappings;
    }

    public override IModelBinder GetBinder(HttpConfiguration configuration, Type modelType)
    {
        IModelBinder binder = null;
        if (_binderMappings.ContainsKey(modelType))
        {
            binder = _container.Resolve(_binderMappings[modelType]) as IModelBinder;

            if (binder == null)
            {
                throw new ComponentNotFoundException(modelType);
            }
        }

        return binder;
    }
}   

YourModelTypeBinder

public class YourModelTypeBinder : IModelBinder
{
    public YourModelTypeBinder(IYourServiceToLoadYourModelType service)
    {
        //...
    }

    public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
    {
        bindingContext.Model = YourCustomCodeToLoadYourModelTypeUsingTheConstructorDependecies(actionContext.Request);
        return true;
    }

    private YourModelType YourCustomCodeToLoadYourModelTypeUsingTheConstructorDependecies(HttpRequestMessage requestMessage)
    {
        ...
    }
}

YourModelTypeBinder будет разрешен контейнером (см. WindsorModelBinderProvider), поэтому вам необходимо сначала его зарегистрировать.

После всего этого подключения ваш контроллер может иметь параметр, среди прочего, как

[ModelBinder]YourModelType user