1

I'm trying to model bind using a model bind provider.

When the GetBinder method is hit I want to serve up a model binder based on what is passed in.

I have a generic model IBaseModel<T> where T : IEntity.

I can grab the BaseModel from the type but what i really want is the <T> on the BaseModel<T> which is an IEntity.

public IModelBinder GetBinder(Type modelType)
{
    Type baseModel = modelType.GetInterface(typeof(IBaseModel<>).Name);

     if (baseModel != null)
     {
         if (baseModel.IsGenericType)
         {
            //want to get <T> (IEntity) here.        
         }
  }

Thanks in advance

tereško
  • 58,060
  • 25
  • 98
  • 150
Hemslingo
  • 272
  • 3
  • 11
  • 2
    possible duplicate of [Reflection - Getting the generic parameters from a System.Type instance](http://stackoverflow.com/questions/293905/reflection-getting-the-generic-parameters-from-a-system-type-instance) – Chris Jul 01 '14 at 14:30
  • Thanks Chris thats exactly what I needed. I wasn't sure how to word my question which is why the answer passed me by. – Hemslingo Jul 01 '14 at 14:35
  • That's cool. As you say its not easy to know what to search for. I knew they were called generic parameters so was able to get there immediately. :) – Chris Jul 01 '14 at 14:38

1 Answers1

0

I understand that you want to get the type of the generic parameter you can try this:

    public static Type GetBinder(Type modelType)
    {
        Type baseModel = modelType.GetInterface(typeof (IBaseModel<>).Name);

        if (baseModel != null)
        {
            if (baseModel.IsGenericType)
            {
                var interfacesTypes = modelType.GetInterfaces();
                var typeGeneric = interfacesTypes.FirstOrDefault(x => x.IsGenericTypeDefinition);
                if (typeGeneric != null)
                {
                    return typeGeneric.GetGenericArguments().First();
                }

            }
        }
        return null;
    }

    public interface IBaseModel<T> where T : IEntity
    {

    }

    public class Musica : IBaseModel<Artista>
    {

    }

    public class Artista : IEntity
    {

    }
renefc3
  • 339
  • 4
  • 17