Home > Blockchain >  Get class and call method of it by string
Get class and call method of it by string

Time:04-07

I have value in appsettings.json where I have matching strategy, it's string

Also I have class that have same name

Here is sample

public class FuzzyCompanyNameStrategy : MatchingScoreCalculationStrategy
{
    public override int CalculateScore(ScoreInputModel input, SupplierModel supplier) =>
        Fuzz.Ratio(input.CompanyName, supplier.SupplierNameNormalized);
}

I code where I need to get this class and method, I have input parameter - name of this Class but it's string.

Here is this class

 protected async Task<MatchingScoreOutput> FindMatch(string name, string postalCode, string city, string matchingStrategy)
        {
            try
            {
                string comparisonName = ComparablePropsHelper.GetComparableCompanyName(name);
                string comparisonPostalCode = ComparablePropsHelper.GetComparablePostalCode(postalCode);
                string comparisonCity = ComparablePropsHelper.GetComparableCityName(city);

                var jobSuppliers = await _dataPipelineDbContext.JobSuppliers.AsNoTracking().ToListAsync();
                
               
                
                return new MatchingScoreOutput
                {
                    MatchFound = true,
                    Confidence = MatchConfidence.HIGH,
                    Score = ,
                };
 }
            catch (Exception ex)
            {
                _logger.LogError(ex,
                    $"{nameof(GenericScoreSupplierComparisonService<TEntity>)}: Exception occurred. Message: {ex.Message}");
                throw;
            }

In Score = I need somehow to call strategy that coming from matchingStrategy and call CalculateScore

How I can do this?

CodePudding user response:

A few ways to do this Use System.Reflection Get the assembly where the types are defined. The Assembly class has a GetType method which takes a string and will return the type. Create an instance of the type, cast it as MatchingScoreCalulationStrategy and call the method. It can get very fiddly this. Personally I prefer to use attributes, then name of the strategy doesn't have to be the class name.

  • Related