Review:
Typically an instantiated object is an instantiation of a class with the new keyword
C# dynamically creates an instance of a class in the class factory using the following methods:
Activator.CreateInstance (Type) Activator.CreateInstance (Type, Object[])
First, we define an ITest interface as follows:
Define two implementation classes, namely: TestA and TestB, and the code is as follows:
where TestB has a non-empty constructor
The GetUserName method in the TestB class needs to read the configuration file through IConfiguration, and then stitch it with the incoming parameters to return the return value.
The configuration file is as follows:
We create objects by dynamically loading the dll, creating them by reflection, and instantiating them through Activator and ActivatorUtilities respectively, with the following code:
Return results:
ret "hello itsvse.com" ex. Message "No parameterless constructor defined for type 'ClassLibrary1.TestB'."
ret "hello itsvse.com" ret "aaaa itsvse.com" When using Activator to create a TestB object, an error is reported:No parameterless constructor defined for type 'ClassLibrary1.TestB'.
Creating TestA and TestB through ActivatorUtilities will not report an error, and the method can be executed normally, as shown below:
There is no problem in using Activator to instantiate objects in the .NET framework, but in asp.net core, the concepts of IOC and DI are introduced, and many objects are not parameterless constructors and need to be passed in the corresponding implementation class.
Where _services static variables are defined as follows:
CreateInstance(IServiceProvider, Type, Object[])
parameter
provider IServiceProvider Service provider for resolving dependencies
instanceType Type The type to activate
parameters Object[]
Constructor parameters that are not provided by the provider。
Reference:The hyperlink login is visible.
(End)
|