lundi 10 août 2020

call c# class method by reflection with constructor using dependency injection

 var fileName = string.Format(@"{0}\{1}\{2}.dll", Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)),"ProviderDLLS", $"UtilityPayments.Providers.TestProvider");
 if (!File.Exists(fileName)) return null;
 AssemblyName an = AssemblyName.GetAssemblyName(fileName);
 Assembly assembly = Assembly.LoadFile(fileName);
 Type objectType = assembly.GetType("UtilityPayments.Providers.TestProvider.Class1");
 IProviderProcessor remoteAssembly = (IProviderProcessor)Activator.CreateInstance(objectType);
 return await remoteAssembly.GetProviderData();

I call class method , which implements IProviderProcessor interface using reflection . if I declare constructor in Class1 class and add interfaces using DI , I get error

System.MissingMethodException: No parameterless constructor defined for type 'UtilityPayments.Providers.TestProvider.Class1'. at System.RuntimeType.CreateInstanceDefaultCtorSlow(Boolean publicOnly, Boolean wrapExceptions, Boolean fillCache) at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, Boolean wrapExceptions)
at System.Activator.CreateInstance(Type type, Boolean nonPublic, Boolean wrapExceptions)

This is Class1 constructor

 public class Class1: IProviderProcessor
        {
            private readonly IProviderService _providerService;
    
            public Class1(IProviderService providerService)
            {
                _providerService = providerService;
            }
    
    }

How can I call Class1 - s methods using reflection if I want to inject interfaces in constructor? code works fine if I remove constructor , but I need to use applications other functionalities in class1, which are implemented using dependency injection.





Aucun commentaire:

Enregistrer un commentaire