![](/img/trans.png)
[英]Unity (dependency injection): How to pass in a parameter to the constructor in RegisterType
[英]How to pass a type as parameter to a constructor when using Unity dependency injection
我們使用Unity依賴注入。 我們有一個需要將類型傳遞給其構造函數的類。
public interface ITest
{
}
public class Test : ITest
{
public Test(Type myType)
{
}
}
在容器boosterapper中,我們注冊類型:
public static IUnityContainer Start()
{
IUnityContainer container = UnityInversionOfControlContainer.RegisterContainer();
container.RegisterType<ITest, Test>();
return container;
}
我們這樣解決:
object actual = container.Resolve<ITest>(new ParameterOverride("myType", typeof(string)));
這給出以下錯誤:
Microsoft.Practices.Unity.ResolutionFailedException:依賴關系的解析失敗,類型=“ ITest”,名稱=“(none)”。 發生以下異常:正在解決。 異常是:InvalidOperationException-無法構造類型String。 您必須配置容器以提供該值。
在發生異常時,容器為:
解析測試,(無)(從Belastingdienst.Omvormers.Mapper.ITest映射,(無))構造函數Test(System.Type myType)的解析參數“ myType”解析System.String,(無)---> System.InvalidOperationException :不能構造字符串類型。 您必須配置容器以提供該值。
似乎unity要通過容器解析類型,並傳入類型的實例,但我確實需要Type。
有人在想嗎?
答案包含在Haukinger發布的鏈接的代碼中:
object actual =
container.Resolve<IDatarecordSerializer>(
new ParameterOverride(
"type",
new InjectionParameter(typeof(string))
)
);
實際上,Unity顯式地將ParameterOverride
Type
值視為文字值,而不是應自行解析的類型。 然后,它嘗試解析類型為string
的實例,但失敗了。
ParameterOverride
將值存儲在InjectionParameterValue
實例中,然后實例將Type
解釋為與其他類型不同的Type
。
參見InjectionParameterValue.cs中的第77ff行
我會嘗試用Unity創建一個問題,但是我想它更多的是功能而不是錯誤。
同時,通過將依賴項的類型更改為以下內容,從Unity中隱藏Type
:
class HiddenType
{
public Type Type
{
get;
}
public HiddenType( Type type )
{
Type = type;
}
}
更簡單的方法是注冊工廠:
給出:
internal interface ITyped
{
Type Type { get; }
}
internal class Typed : ITyped
{
public Typed(Type type)
{
Type = type;
}
public Type Type { get; }
}
數量:
internal class TypedFactory : ITypedFactory
{
public ITyped Create(Type type)
{
return new Typed(type);
}
}
internal interface ITypedFactory
{
ITyped Create(Type type);
}
container.RegisterType<ITypedFactory, TypedFactory>();
Assert.AreEqual(
container.Resolve<ITypedFactory>().Create(typeof(string)).Type,
typeof(string));
不是火箭科學,而是簡單,明顯且易於調試
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.