1

I have a C# class which looks like this:

public class SpproRepository<T> : IRepository where T : ISpproEntity
{
  // Code here
}

and I have a context class which looks like this

public class SeymourSpContext : SpproBaseContext
{
    public virtual SpproRepository<Properties> Properties { get; set; }
}

Now I am trying to instantiate all my Properties which are of type SpproRepository (where I dont define T, except that it implements ISpproEntity.

My problem is simply that I can not figure out how to check if property is of type SpproRepository

Here is one of my many attempts:

    public SpproBaseContext(string siteUrl)
    {
        var type = this.GetType();      
        foreach (var property in type.GetProperties())     //Itterate Through all properties, if they are type SpproRepository instantiate        
        {                
            if (property.PropertyType.GetInterfaces().Where(a=> a.GetType() == typeof(IRepository)).Any())   //I Implemented IRepository as a test, this didnt work. Ideally it would be something like Property.PropertyType is SpproRepository<>; but this doesnt either
            {
                 //code below here works as it should
                var listType = typeof(SpproRepository<>);
                var genericArgs = property.PropertyType.GetGenericArguments();
                var concreteType = listType.MakeGenericType(genericArgs);
                var listName = genericArgs[0].Name;
                var newRepo = Activator.CreateInstance(concreteType, listName);
                property.SetValue(this, newRepo);
            }
        }

    }
Michael
  • 8,229
  • 20
  • 61
  • 113
  • 2
    how about creating a non-generic abstract class `SpproRepository` and inheriting it like this: `public class SpproRepository : SpproRepository`. Then you can check if your property derives from `SpproRepository` easily – Khanh TO Jul 07 '17 at 14:15
  • I've also tried this but I still cant seem to compare the objects. I have added the SpproRepository inheritance and then checked with this : property.PropertyType.IsAssignableFrom(typeof(SpproRepository) but its still falsey – Michael Jul 07 '17 at 14:33
  • but this works :) if (typeof(SpproRepository).IsAssignableFrom(property.PropertyType)) – Michael Jul 07 '17 at 14:34

0 Answers0