dependency-injectioncastle-windsor.net-5

What's the equivalent of the DictionaryAdapterFactory of Windsor in IHostBuilder?


I am moving a console application from .NET 4.6 to .NET 5. At the same time the idea is to get rid of Castle.Windsor and start using the builtin Dependency Injection present in Microsoft.Extensions.

I will be honest. I am not used to either of them. The application has an IApplicationConfiguration that is a representation of what we need from the app.config file.

How do I translate it to IHostBuilder?

Thanks in advance


Solution

  • Right, after investigating this, I found a solution using reflection.

    Here is an example:

    using System;
    using System.Reflection;
    using System.Reflection.Emit;
    
    namespace TestConsoleNet5
    {
        public class Program
        {
            public static void Main()
            {
                AssemblyName aName = new AssemblyName("DynamicAssemblyExample");
    
                AssemblyBuilder ab =
                    AssemblyBuilder.DefineDynamicAssembly(
                        aName,
                        AssemblyBuilderAccess.RunAndCollect);
                ModuleBuilder mb =
                    ab.DefineDynamicModule(aName.Name + "Module");
                TypeBuilder tb = mb.DefineType(
                    "MyDynamicType",
                     TypeAttributes.Public);
    
                BuildPropertyAndConstructor(tb, "This is a test");
    
                tb.AddInterfaceImplementation(typeof(ITest));
                var type = tb.CreateType();
                ITest test = Activator.CreateInstance(type) as ITest;
                Console.WriteLine(test.propTest);
            }
    
            private static void BuildPropertyAndConstructor(TypeBuilder typeBuilder, string defaultValue)
            {
                string propName = "propTest";
                FieldBuilder field = typeBuilder.DefineField("m" + propName, typeof(string), FieldAttributes.Private);
                PropertyBuilder propertyBuilder = typeBuilder.DefineProperty(propName, PropertyAttributes.None, typeof(string), null);
    
                MethodAttributes getSetAttr = MethodAttributes.Public |
                    MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.Virtual;
    
                MethodBuilder getter = typeBuilder.DefineMethod("get_" + propName, getSetAttr, typeof(string), Type.EmptyTypes);
    
                ILGenerator getIL = getter.GetILGenerator();
                getIL.Emit(OpCodes.Ldstr, defaultValue);
                getIL.Emit(OpCodes.Ret);
    
    
                propertyBuilder.SetGetMethod(getter);
            }
        }
        public interface ITest
        {
            string propTest { get; }
        }
    }
    
    

    So, where you find "This is a test" you should pass the value from the config file.

    Also the interface should be the IApplicationConfiguration

    It is a bit messy but it works.