问题描述
我正在将控制台应用程序从 .NET 4.6 迁移到 .NET 5。 同时,这个想法是摆脱 Castle.Windsor 并开始使用 Microsoft.Extensions 中的内置依赖注入。
我会诚实的。我不习惯他们中的任何一个。该应用程序有一个 IApplicationConfiguration,它表示我们需要从 app.config 文件中获取的内容。
如何将其翻译成 IHostBuilder?
提前致谢
解决方法
对,经过调查,我找到了一个使用反射的解决方案。
这是一个例子:
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,null);
MethodAttributes getSetAttr = MethodAttributes.Public |
MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.Virtual;
MethodBuilder getter = typeBuilder.DefineMethod("get_" + propName,getSetAttr,Type.EmptyTypes);
ILGenerator getIL = getter.GetILGenerator();
getIL.Emit(OpCodes.Ldstr,defaultValue);
getIL.Emit(OpCodes.Ret);
propertyBuilder.SetGetMethod(getter);
}
}
public interface ITest
{
string propTest { get; }
}
}
因此,在您找到“这是一个测试”的地方,您应该传递配置文件中的值。
接口也应该是 IApplicationConfiguration
它有点乱,但它有效。