In the past I ve used and abused Dependency Injection with Biztalk ESB Toolkit, MEL and .NET . Today I want to use Dependency Injection with Core .Net.
I m using .Net 7.0.
My configuration must be dynamic, in a config file. I want to be able to add functionalities to my code by adding new assemblies.
References
A simgle Refenrece has been added to the project : Microsoft.Extensions.DependencyInjection
Config File
To make it very simple, I have just added a new section components that will contain a collection of name-value pairs.
each entry contains a Key, which is the name I will use to reference the class I want to use to initiate in my code, and a value which contains the name of the assembly and the fullname of the class.
In this example, the assembly is Project.Name.dll.
And the class project.namespace.classname1.
Reading the config file
In my application, I will read the config file and initialize a dictionnary with the name of the component as Key, and a structure of data with the Name, the Assembly and the ClassName. The Name could be removed.
The GetConfig method is called only once, all the
privatestructFactoryItem{publicstringName;publicstringAssembly;publicstringClass;}...privatestaticDictionary<string,FactoryItem>_components_=null;privatestaticvoidGetConfig(){NameValueCollectionpending=null;string[]strings;if(null!=ConfigurationManager.GetSection("components")){if(null==_components)_components=newDictionary<string,FactoryItem>();pending=ConfigurationManager.GetSection("components")asNameValueCollection;foreach(stringkeyinpending.AllKeys){strings=pending[key].ToString().Split(',');_components.Add(key,newFactoryItem(){Name=key,Assembly=strings[0],Class=strings[1]});}}elsethrownewException("Missing components section in config file");pending=null;}
Factory Create
In my factory, I have created a method to Instatiate dynamically my classes, my constructors requiring some parameters.
1
2
3
4
5
6
7
8
9
10
11
publicstaticTCreate<T>(stringassemblyName,stringclassName,Dictionary<string,string>parameters,Dictionary<string,string>context,List<string>result)whereT:class{Assemblyassembly=Assembly.Load(assemblyName);T?o=assembly.CreateInstance(className,true,BindingFlags.Default,null,newobject[]{parameters,context,result},null,null)asT;if(null==o){thrownewException($"Unable to create instance of {className} from {assemblyName}");}returno;}
The parameters required must be provided in : new object[] { parameters, context, result }
Next optimization is to keep a list of assemblies already loaded.