jeudi 6 janvier 2022

Reflection, set.GetValue(context, null) always return null

I'm trying to get a property from an object by reflection.

public class CosmosDbSet<TEntity> : DbSet<TEntity> where TEntity : class, IEntity<string>
{
    public string Name { get; }
    //...
        );

}

public class SKCosmosDbContext : CosmosDBContext
{
    public CosmosDbSet<Item> Items { get; }

   public SKCosmosDbContext ()
   {
        Items = new CosmosDbSet<Item>(
            this,
            "Items"
        );
   }
    //...
}

public abstract class CosmosDBContext : DbContext
{
    public async Task EnsureContainersExistAsync()
    {
            var sets = GetType().GetProperties()
                .Where(pi => pi.PropertyType.IsGenericType
                    && pi.PropertyType.GetGenericTypeDefinition().Equals(typeof(CosmosDbSet<>))
                );
            foreach (var set in sets)
            {
                var value = set.GetValue(this, null); // => value is always null
                //...
            }
    }
}

public static class DbInitializer
{
    public async static Task InitializeAsync(IServiceProvider services, ILogger logger)
    {
        var dbContext = services.GetRequiredService<SKCosmosDbContext>();
        await dbContext.EnsureContainersExistAsync();
    }
}

As you can see, the property Items from SKCosmosDbContext has been found but, I can't have access to it. Description

How to have access to the property using reflection?





Aucun commentaire:

Enregistrer un commentaire