dimanche 3 février 2019

How Can I Avoid Using Magic Strings in my MVC CustomModelBinding?

I have a method that determines the concrete type to instantiate for an abstract type based on the value of a property:

private static Type GetModelType(ControllerContext controllerContext, 
    ModelBindingContext bindingContext, Type modelType)
{
    if (modelType != typeof(MyAbstractClass)) return modelType;

    var key = "MyAbstractClass.ConcreteTypeEnum";
    if (bindingContext.ValueProvider.ContainsPrefix(key))
    {
        var concreteTypeName = bindingContext.ValueProvider.GetValue(key).AttemptedValue;
        modelType = Type.GetType(
          $"MySolution.ANamespace.InAnother.Project.Models.{concreteTypeName}, {modelType.Assembly}" );
        }
    }
    return modelType;
}

  1. How can I (using reflection, probably) determine the name of the property "MyAbstractClass.ConcreteTypeEnum" without using a string to find it? If someone renames the property I don't want my modelbinding to break.
  2. MyAbstractClass and the concrete classes are in the same namespace, MySolution.ANamespace.InAnother.Project.Models.*. How can I draw that namespace from MyAbstractClass to keep from using a string here as well?




Aucun commentaire:

Enregistrer un commentaire