Да, это возможно. Вам следует создать класс создания из System.Web.Mvc.CustomModelBinder
и переопределить метод GetBinder
. Например, здесь реализация, которая принимает в дополнение к Type
объекту, а также массив объектов для параметров конструктора связывателя модели:
public sealed class MyModelBinderAttribute : CustomModelBinderAttribute
{
/// <summary>
/// Gets or sets the type of the binder.
/// </summary>
/// <returns>The type of the binder.</returns>
public Type BinderType { get; }
/// <summary>
/// Gets or sets the parameters for the model binder constructor.
/// </summary>
public object[] BinderParameters { get; }
/// <summary>
/// Initializes a new instance of the <see cref="T:System.Web.Mvc.ModelBinderAttribute" /> class.
/// </summary>
/// <param name="binderType">The type of the binder.</param>
/// <param name="binderParameters">The parameters for the model binder constructor.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="binderType" /> parameter is null.</exception>
public MyModelBinderAttribute(Type binderType, params object[] binderParameters)
{
if (null == binderType)
{
throw new ArgumentNullException(nameof(binderType));
}
if (!typeof(IModelBinder).IsAssignableFrom(binderType))
{
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture,
"An error occurred when trying to create the IModelBinder '{0}'. Make sure that the binder has a public parameterless constructor.",
binderType.FullName), nameof(binderType));
}
this.BinderType = binderType;
this.BinderParameters = binderParameters ?? throw new ArgumentNullException(nameof(binderParameters));
}
/// <summary>Retrieves an instance of the model binder.</summary>
/// <returns>A reference to an object that implements the <see cref="T:System.Web.Mvc.IModelBinder" /> interface.</returns>
/// <exception cref="T:System.InvalidOperationException">An error occurred while an instance of the model binder was being created.</exception>
public override IModelBinder GetBinder()
{
IModelBinder modelBinder;
try
{
modelBinder = (IModelBinder)Activator.CreateInstance(this.BinderType, this.BinderParameters);
}
catch (Exception ex)
{
throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture,
"An error occurred when trying to create the IModelBinder '{0}'. Make sure that the binder has a public parameterless constructor.",
this.BinderType.FullName), ex);
}
return modelBinder;
}
}