vendredi 5 novembre 2021

Call method dynamically of class C#

I am trying to call a GetAll method, which is implemented in different classes. Which class I have to invoke is done dynamically. I am using autofac, so if I try to create the instance with the activator, im getting Cannot create an instance of an interface. I also tried to invoke the method with MethodInfo invoke, but it only works if the class is already instantiated, but it is not dynamic in runtime. Is there any way to dynamically call methods of classes I already have instantiated?

private readonly IChangeLogRecoverAndPersists _changeLogRecoverAndPersists;
private readonly IRewardTypeRecoverAndPersists _rewardTypeRecoverAndPersists;
private readonly IMapper _mapper;

public ChangeLogService(IChangeLogRecoverAndPersists changeLogRecoverAndPersists,
    IRewardTypeRecoverAndPersists rewardTypeRecoverAndPersists,
    IMapper mapper)
{
    _changeLogRecoverAndPersists = changeLogRecoverAndPersists;
    _rewardTypeRecoverAndPersists = rewardTypeRecoverAndPersists;
    _mapper = mapper;
}


private void MapProperties(ref List<ChangeLogDTO> changes)
{
    var assembly = typeof(IChangeLogRecoverAndPersists).GetTypeInfo().Assembly;
    Type[] typelist = GetTypesInNamespace(assembly, "Test.Config.Library.InfrastructureContracts");

    foreach (var change in changes)
    {
        var changeEntity = JsonConvert.DeserializeObject(change.NewValue, GetType(change.EntityName));

        foreach (var prop in changeEntity.GetType().GetProperties())
        {
            var propName = prop.Name.ToLower();

            if (!propName.Equals("id") && prop.PropertyType == typeof(Guid))
            {
                var propValue = prop.GetValue(changeEntity, null);
                propName = propName.Replace("id", string.Empty);

                var recoverAndPersistsType = typelist
                    .Where(tl => tl.Name.ToLower().Contains(propName))
                    .FirstOrDefault();

                if (recoverAndPersistsType is null)
                    continue;

                var method = recoverAndPersistsType.GetMethod("GetAll");
                
                //It works but it is not dynamic
                var result = method.Invoke(_rewardTypeRecoverAndPersists, null);
            }
        }
    }
}




Aucun commentaire:

Enregistrer un commentaire