我遇到以下問題與Unity框架。統一BuildUp失敗的單身人士
我們在我們的項目中有一個singleton類。他們有一些屬性應該由Unity容器注入。下面是代碼:
private static SomeClass m_Instance;
private SomeClass()
{ }
public static SomeClass Instance
{
get
{
if (m_Instance == null)
{
lock (typeof(SomeClass))
{
if (m_Instance == null)
{
IUnityContainer container = ContainerAccessor.GetContainer();
m_Instance = container.BuildUp<SomeClass>(new SomeClass());
}
}
}
return m_Instance;
}
}
此代碼失敗,出現以下異常:類型SomeClass的無法構造。您必須配置容器以提供此值。
我已經挖成統一的代碼並發現問題是由方法PreBuildUp,它調用GuardTypeIsNonPrimitive,無論是在Microsoft.Practices.ObjectBuilder2.DynamicMethodConstructorStrategy類中定義引起的。這是它的代碼片段:
public override void PreBuildUp(IBuilderContext context)
{
...
SelectedConstructor selectedConstructor = context.Policies.Get<IConstructorSelectorPolicy>(context.BuildKey, out list).SelectConstructor(context, list);
GuardTypeIsNonPrimitive(context, selectedConstructor);
...
}
private static void GuardTypeIsNonPrimitive(IBuilderContext context, SelectedConstructor selectedConstructor)
{
Type type = context.BuildKey.Type;
if (!type.IsInterface && ((type == typeof(string)) || (selectedConstructor == null)))
{
throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Resources.TypeIsNotConstructable, new object[] { type.Name }));
}
}
正如我們所看到的,Unity試圖找到應構建的類的構造函數。由於爲SomeClass定義的唯一構造函數是私有的,因此Unity找不到任何內容,並將null傳遞給GuardTypeIsNonPrimitive。而這種方法會引發異常。目前我已經定義了SomeClass的公共構造函數(只是爲了證明這個概念),一切都很好。
問題:
UPDATE:爲什麼要定義方法需要構造的積累?
任何想法如何解決這個問題? (刪除單是不是一種選擇)
+1是的,使用容器來保存你的單身人士。這是你擁有容器的原因之一。 – PVitt 2011-05-13 11:03:00
如果我錯了,請糾正我,但您的建議似乎認爲SomeClass已在容器中註冊。但它不是,也不會是,這就是我們在這裏試圖使用BuildUp方法的原因。 – Andrei 2011-05-13 11:04:21
然後你必須提供一個容器的構造函數。 – PVitt 2011-05-13 11:09:45