我有一个带有内部构造函数的类,想从 Unity (2.0) 中解析它。
public class MyClass {
internal MyClass(IService service) {
}
}
那我在做
_container.Resolve<MyClass>();
当我这样做时我有一个异常(exception)
Exception is: InvalidOperationException - The type MyClass cannot be constructed.
IService 已注册,唯一的问题是构造函数是内部的。
我真的希望这个类是公开的,但我希望它只能通过工厂创建(我实际上在其中调用 container.Resolve<MyClass>()
)。
有没有办法让 Unity 看到那个内部构造函数?比如 InternalsVisibleTo 之类的?
最佳答案
我深入研究了如何为此目的扩展 Unity,并发现了一些有趣的信息。
首先,似乎 Unity 通过内部解析 IConstructorSelectorPolicy
来选择使用哪个构造函数.包含在 Unity 中的是 public abstract class ConstructorSelectorPolicyBase<TInjectionConstructorMarkerAttribute>
,其中包括这个 gem:
/// <summary>
/// Choose the constructor to call for the given type.
/// </summary>
/// <param name="context">Current build context</param>
/// <param name="resolverPolicyDestination">The <see cref='IPolicyList'/> to add any
/// generated resolver objects into.</param>
/// <returns>The chosen constructor.</returns>
public SelectedConstructor SelectConstructor(IBuilderContext context, IPolicyList resolverPolicyDestination)
{
Type typeToConstruct = context.BuildKey.Type;
ConstructorInfo ctor = FindInjectionConstructor(typeToConstruct) ?? FindLongestConstructor(typeToConstruct);
if (ctor != null)
{
return CreateSelectedConstructor(context, resolverPolicyDestination, ctor);
}
return null;
}
FindInjectionConstructor
和公司是private static
此类中最终调用 Type.GetConstructors
的方法(没有参数的重载,只返回 public
构造函数)。这告诉我,如果您可以安排 Unity 使用您自己的构造函数选择器策略,这将能够选择任何构造函数,那么您就是黄金。
有good documentation关于如何制作和使用您自己的容器扩展,所以我想很有可能制作您自己的 CustomConstructorSelectorPolicy
其中包括 DefaultUnityConstructorSelectorPolicy
的相关部分(它派生自抽象基类并且是默认值,除非您注册其他东西)和 ConstructorSelectorPolicyBase
(直接从中派生可能效果不佳,因为关键方法不是 virtual
,但您可以重用代码)。
因此我认为它是可行的,但从工程的角度来看,最终结果将是相当“纯粹”的。
关于c# - UnityContainer 和内部构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6412224/