在C#中使用反射和泛型属性

时间:2013-04-17 14:55:52

标签: c# asp.net-mvc reflection

我的ASP.NET MVC应用程序中有一个接口/类,其中引用了所有通用存储库。这看起来像这样:

public interface IDb
{
    IGenericRepository<Car> CarRepository { get; }
    ...
    IGenericRepository<User> UserRepository { get; }
}

我的目标是在程序集中查找实现某个接口的所有类型,然后找到相应的通用存储库以从数据库中获取某些对象。这应该有效:

List<IVehicle> vehicleElements = new List<IVehicle>();

Type vehicleType = typeof(IVehicle);
Type dbType = typeof(IDb);
foreach (Type type in vehicleType.Assembly.GetTypes().Where(t => t.IsClass && t.GetInterfaces().Contains(vehicleType)))
    {
        PropertyInfo repositoryInfo = dbType.GetProperties().Where(p => p.PropertyType.GenericTypeArguments.Contains(type)).SingleOrDefault();
        if (repositoryInfo != null)
        {
            var repository = repositoryInfo.GetValue(this.db);
            // TODO: work with repository
        }
    }

return vehicleElements;

我的问题是我不知道如何将存储库变量转换为所需的通用IGenericRepository ...任何想法?

2 个答案:

答案 0 :(得分:0)

您想要做的事情是行不通的,因为为了拥有一个stronlgy类型的存储库,您需要在编译时知道实现您的接口的类型。但是你只能在运行时知道它。

一种解决方案是引入非通用存储库。

另一种解决方案是使用dynamic关键字。

dynamic repository = repositoryInfo.GetValue(this.db);
repository.SomeMethod(...);

但是,这意味着编译器不再能够检查涉及此动态变量的代码。换句话说:如果实际类型SomeMethod上不存在repository,则会抛出运行时异常,而不是编译器错误。

答案 1 :(得分:0)

我会使用基本的IRepository接口,使用您需要在此代码中进行交互的常用方法。

如果出于某种原因这是不可能的,你可以采用松散耦合的方法,通过反射来动态或抓住你需要的方法。