gpt4 book ai didi

c# - Unity 无法解析基本依赖链

转载 作者:太空狗 更新时间:2023-10-29 17:55:01 25 4
gpt4 key购买 nike

我正在 Unity IoC 中实现程序集的动态加载和注册。

给定这些类:

public interface IA { }
public interface IB { }
public interface IC { }

public class A : IA { }
public class B : IB
{
public B(IA a) { }
}

public class C : IC
{
public C(IB b) { }
}

这个配置:

var assembly = Assembly.LoadFile(@"path\MyAsm.dll");
container.RegisterTypes(
AllClasses.FromAssemblies(assembly),
WithMappings.FromAllInterfacesInSameAssembly,
WithName.Default,
WithLifetime.Transient);

代码:

var c = container.Resolve(typeof(IC));

抛出:

A first chance exception of type 'Microsoft.Practices.Unity.ResolutionFailedException' occurred in Microsoft.Practices.Unity.dll

Additional information: Resolution of the dependency failed, type = "MyAsm.IC", name = "(none)".

Exception occurred while: while resolving.

Exception is: InvalidOperationException - The type IC does not have an accessible constructor.


At the time of the exception, the container was:

MyAsm.IC,(none)

以上所有代码都在同一个程序集 MyAsm 中执行。在调试中分析容器,Registrations属性列出似乎是 A 映射的正确集合, BC到他们各自的界面以及他们自己。

有什么想法吗?

解决方案

在 Tyler 的回应之后我改变了:

var assembly = Assembly.LoadFile(@"path\MyAsm.dll");

var assembly = Assembly.LoadFrom(@"path\MyAsm.dll");

解决了这个问题。 Assembly上的这两个方法具有相同的参数和相同的返回类型和 vary just slightly in behavior . 纯粹的邪恶

最佳答案

我能够重现您遇到的错误。

因此,您从文件 Assembly.LoadFile(@"path\MyAsm.dll"); 加载程序集,然后解析硬引用类型 container.Resolve(类型(IC));。我相信这些类型来自两个不同的编译二进制文件。 @"path\MyAsm.dll"中二进制文件的类型已加载到容器中,但您正试图从应用程序路径的 bin 目录中解析二进制文件的类型(引用的程序集 CopyLocal 设置为 True)。

您需要从已加载到应用程序域中的引用二进制文件中注册类型,或者您需要使用反射从已加载的二进制文件中解析类型以查找类型。

var assembly = AppDomain.CurrentDomain.GetAssemblies().
SingleOrDefault(asm => asm.GetName().Name == "MyAsm");
...
var c = container.Resolve(typeof(IC));

——或者——

var assembly = Assembly.LoadFile(@"path\MyAsm.dll");
...
var c = container.Resolve(assembly.GetType("MyAsm.IC"));

关于c# - Unity 无法解析基本依赖链,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22159466/

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