gpt4 book ai didi

c# - Unity 无法解析动态创建类的实例

转载 作者:行者123 更新时间:2023-11-30 22:42:18 24 4
gpt4 key购买 nike

解决方案我没有在新类型上指定构造函数参数,因此 .NET 假设了基类的类型,但是它也没有将它们命名为相同的,所以当 Unity 尝试 Parameter[x].Name 时,它​​得到了一个 Null 值参数名称。

抱歉使用“U”这个词,但这确实是一个问题,我需要紧急解决这个问题以解决其他地方的大量内存泄漏(长话短说。)所以如果有人可以帮助解决这个问题,我将非常感激!

我在运行时使用 Reflection.Emit 动态创建类型。动态类型派生自运行时指定的基类型,并实现 IController。目的是用 try...finally 包装对 IController.Execute 的调用并处理一个对象。

奇怪的是。我可以像这样创建这种新类型的实例

var requiredDependency = new Logger();
Type interceptingControllerType = CreateInterceptingControllerType(superClass);
var constructorInfo = interceptingControllerType.GetConstructor(new Type[] { typeof(Logger) });
var result = (IController)constructorInfo.Invoke(new object[] { requiredDependency });

我也可以像这样使用 unity 来解析父类(super class)

var superClassThatWillResolve = container.Resolve(superClass);

但是我无法使用unity来解析动态创建的子类

var newSubClassThatWontResolve = container.Resolve(interceptingControllerType);

当我尝试后者时,出现以下异常

Microsoft.Practices.Unity.ResolutionFailedException was unhandled
Message=Resolution of the dependency failed, type = "9d206a0c-2c78-43d1-8907-8227ad1242f1", name = "(none)".
Exception occurred while: while resolving.
Exception is: ArgumentNullException - Value cannot be null.
Parameter name: str
-----------------------------------------------
At the time of the exception, the container was:

Resolving 9d206a0c-2c78-43d1-8907-8227ad1242f1,(none)

Source=Microsoft.Practices.Unity
TypeRequested=9d206a0c-2c78-43d1-8907-8227ad1242f1
StackTrace:
at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides)
at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, String name, IEnumerable`1 resolverOverrides)
at Microsoft.Practices.Unity.UnityContainer.Resolve(Type t, String name, ResolverOverride[] resolverOverrides)
at Microsoft.Practices.Unity.UnityContainerExtensions.Resolve(IUnityContainer container, Type t, ResolverOverride[] overrides)
at ConsoleApplication18.InterceptingControllerBuilder.CreateControllerInterceptor(IUnityContainer container, Type superClass) in C:\Users\PeterMorris\Documents\Visual Studio 2010\Projects\ConsoleApplication18\InterceptingControllerBuilder.cs:line 24
at ConsoleApplication18.Program.Main(String[] args) in C:\Users\PeterMorris\Documents\Visual Studio 2010\Projects\ConsoleApplication18\Program.cs:line 15
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException: System.ArgumentNullException
Message=Value cannot be null.
Parameter name: str
Source=mscorlib
ParamName=str
StackTrace:
at System.Reflection.Emit.DynamicILGenerator.Emit(OpCode opcode, String str)
at Microsoft.Practices.ObjectBuilder2.DynamicMethodConstructorStrategy.PreBuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlanCreatorPolicy.CreatePlan(IBuilderContext context, NamedTypeBuildKey buildKey)
at Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)
at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides)
InnerException:

这是测试代码...

using System;
using Microsoft.Practices.Unity;

namespace ConsoleApplication18
{
class Program
{
static void Main(string[] args)
{
var container = new UnityContainer();
var childContainer = container.CreateChildContainer();
IController interceptingController = InterceptingControllerBuilder.CreateControllerInterceptor(
childContainer, typeof(CountryController));
try
{
interceptingController.Execute("Hello");
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
Console.ReadLine();
}
}

public class Logger
{
public void Log(string text)
{
Console.WriteLine(text);
}
}

public interface IController
{
void Execute(string text);
}

public class Controller : IController
{
readonly Logger Logger;

public Controller(Logger logger)
{
Logger = logger;
}

public virtual void Execute(string text)
{
Logger.Log("Controller: " + text);
}
}

public class CountryController : Controller
{
public CountryController(Logger logger)
: base(logger)
{
}

public override void Execute(string text)
{
base.Execute("CountryController: " + text);
}
}
}

以及实现代码

using Microsoft.Practices.Unity;

namespace ConsoleApplication18
{
public interface IUnityContainerController
{
IUnityContainer IUnityContainerController_UnityContainer { get; set; }
}
}




using System;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using Microsoft.Practices.Unity;

namespace ConsoleApplication18
{
public static class InterceptingControllerBuilder
{
const string UnityContainerBackingFieldName = "IUnityContainerController_BackingField";
static MethodInfo DisposeMethodInfo = typeof(IDisposable).GetMethod("Dispose");

public static IController CreateControllerInterceptor(IUnityContainer container, Type superClass)
{
var requiredDependency = new Logger();
Type interceptingControllerType = CreateInterceptingControllerType(superClass);
var constructorInfo = interceptingControllerType.GetConstructor(new Type[] { typeof(Logger) });
var result = (IController)constructorInfo.Invoke(new object[] { requiredDependency });
var resultAsIUnityContainerController = (IUnityContainerController)result;
resultAsIUnityContainerController.IUnityContainerController_UnityContainer = container;

var superClassThatWillResolve = container.Resolve(superClass);
var newSubClassThatWontResolve = container.Resolve(interceptingControllerType);

return result;
}

static Type CreateInterceptingControllerType(Type superClass)
{
if (!typeof(IController).IsAssignableFrom(superClass))
throw new ArgumentException("SuperClass does not implement IController");

string guid = Guid.NewGuid().ToString();
var assemblyName = new AssemblyName(guid);
var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(
assemblyName,
AssemblyBuilderAccess.Run);
var moduleBuilder = assemblyBuilder.DefineDynamicModule(guid);
var typeBuilder = moduleBuilder.DefineType(
guid,
TypeAttributes.Class | TypeAttributes.Public,
superClass);
CreateConstructor(superClass, typeBuilder);
FieldBuilder unityContainerBackingFieldBuilder;
ImplementIUnityContainerController(typeBuilder, out unityContainerBackingFieldBuilder);
ImplementIController(superClass, typeBuilder, unityContainerBackingFieldBuilder);
return typeBuilder.CreateType();
}

static void CreateConstructor(Type superClass, TypeBuilder typeBuilder)
{
var constructorInfo = superClass.GetConstructors()
.OrderByDescending(x => x.GetParameters().Count())
.FirstOrDefault();
if (constructorInfo == null)
return;
ParameterInfo[] constructorParameters =
constructorInfo.GetParameters().ToArray();
Type[] parameterTypes = constructorParameters.Select(x => x.ParameterType).ToArray();
var constructorBuilder = typeBuilder.DefineConstructor(
MethodAttributes.Public,
CallingConventions.Standard,
parameterTypes);
var bodyGenerator = constructorBuilder.GetILGenerator();
bodyGenerator.Emit(OpCodes.Ldarg_0);
for (int argumentIndex = 0; argumentIndex < constructorParameters.Count(); argumentIndex++)
bodyGenerator.Emit(OpCodes.Ldarg, argumentIndex + 1);
bodyGenerator.Emit(OpCodes.Call, constructorInfo);
bodyGenerator.Emit(OpCodes.Ret);
}

static void ImplementIUnityContainerController(TypeBuilder typeBuilder, out FieldBuilder unityContainerBackingFieldBuilder)
{
typeBuilder.AddInterfaceImplementation(typeof(IUnityContainerController));
unityContainerBackingFieldBuilder = typeBuilder.DefineField(
UnityContainerBackingFieldName,
typeof(IUnityContainer),
FieldAttributes.Private);

var propertyAccessorAttributes =
MethodAttributes.Public | MethodAttributes.SpecialName |
MethodAttributes.HideBySig | MethodAttributes.Virtual;

var getterBuilder = typeBuilder.DefineMethod(
"get_IUnityContainerController_UnityContainer",
propertyAccessorAttributes,
typeof(IUnityContainer),
Type.EmptyTypes);
var getterGenerator = getterBuilder.GetILGenerator();
getterGenerator.Emit(OpCodes.Ldarg_0);
getterGenerator.Emit(OpCodes.Ldfld, unityContainerBackingFieldBuilder);
getterGenerator.Emit(OpCodes.Ret);

var setterBuilder = typeBuilder.DefineMethod(
"set_IUnityContainerController_UnityContainer",
propertyAccessorAttributes,
null,
new Type[] { typeof(IUnityContainer) });
var setterGenerator = setterBuilder.GetILGenerator();
setterGenerator.Emit(OpCodes.Ldarg_0);
setterGenerator.Emit(OpCodes.Ldarg_1);
setterGenerator.Emit(OpCodes.Stfld, unityContainerBackingFieldBuilder);
setterGenerator.Emit(OpCodes.Ret);
}

static void ImplementIController(Type superClass, TypeBuilder typeBuilder, FieldBuilder unityContainerBackingFieldBuilder)
{
typeBuilder.AddInterfaceImplementation(typeof(IController));
MethodInfo interfaceMethod = typeof(IController).GetMethod("Execute");
InterfaceMapping mapping = superClass.GetInterfaceMap(typeof(IController));
MethodInfo baseMethod = mapping.TargetMethods.Single();

var methodBuilder = typeBuilder.DefineMethod(
typeof(IController).Name + ".Execute",
MethodAttributes.Public | MethodAttributes.Virtual |
MethodAttributes.ReuseSlot | MethodAttributes.HideBySig,
null,
new Type[] { typeof(string) });
var bodyGenerator = methodBuilder.GetILGenerator();
bodyGenerator.BeginExceptionBlock();
bodyGenerator.Emit(OpCodes.Ldarg_0);
bodyGenerator.Emit(OpCodes.Ldarg_1);
bodyGenerator.Emit(OpCodes.Call, baseMethod);
bodyGenerator.BeginFinallyBlock();
bodyGenerator.Emit(OpCodes.Ldarg_0);
bodyGenerator.Emit(OpCodes.Ldfld, unityContainerBackingFieldBuilder);
bodyGenerator.Emit(OpCodes.Call, DisposeMethodInfo);
bodyGenerator.EndExceptionBlock();
bodyGenerator.Emit(OpCodes.Ret);
typeBuilder.DefineMethodOverride(methodBuilder, interfaceMethod);
}
}
}

最佳答案

新类型的构造函数的参数未定义,因此 .NET 创建了一些名称为 NULL 的默认参数!

//Define the parameters for our new constructor
for (int argumentIndex = 0; argumentIndex < parameterTypes.Length; argumentIndex++)
constructorBuilder.DefineParameter(
argumentIndex + 1,
constructorParameters[argumentIndex].Attributes,
constructorParameters[argumentIndex].Name);

关于c# - Unity 无法解析动态创建类的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4479760/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com