为什么 Unity 自定义 BuilderStrategy 即使在设置现有属性后仍返回 null
我正在使用 Unity 版本 2(随 Prism4 一起提供)。我正在尝试编写一个可以返回非注册类型的可枚举扩展。以下代码是我编写的,但在解析调用后我得到空值。
class EnumerableStrategy : BuilderStrategy
{
public override void PreBuildUp(IBuilderContext context)
{
context.Existing = new []{"Test"};
context.BuildComplete = true;
}
}
class EnumerableExtension : UnityContainerExtension
{
protected override void Initialize()
{
Context.BuildPlanStrategies.AddNew<EnumerableStrategy>( Microsoft.Practices.Unity.ObjectBuilder.UnityBuildStage.PreCreation);
}
}
static void Main(string[] args)
{
var container = new UnityContainer();
container.AddNewExtension<EnumerableExtension>();
var items = container.Resolve<IEnumerable<string>>();
foreach (var item in items)
Console.WriteLine(item.ToString());
}
Items 变量结果为空。为什么?
I'm using version 2 of Unity (that comes with Prism4). I'm trying to write an extension that can return enumerable of a non registered type. Following code is what I've written but I'm getting null after resolve call.
class EnumerableStrategy : BuilderStrategy
{
public override void PreBuildUp(IBuilderContext context)
{
context.Existing = new []{"Test"};
context.BuildComplete = true;
}
}
class EnumerableExtension : UnityContainerExtension
{
protected override void Initialize()
{
Context.BuildPlanStrategies.AddNew<EnumerableStrategy>( Microsoft.Practices.Unity.ObjectBuilder.UnityBuildStage.PreCreation);
}
}
static void Main(string[] args)
{
var container = new UnityContainer();
container.AddNewExtension<EnumerableExtension>();
var items = container.Resolve<IEnumerable<string>>();
foreach (var item in items)
Console.WriteLine(item.ToString());
}
Items variable turns out to be null. Why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将策略添加到 Strategies 集合中,而不是 BuildPlanStrategies 中。
BuildPlanStrategies 用于构造将构造解析对象的对象。这不是你正在做的——你只是直接返回对象。实际上,我很惊讶你得到了 null - 我本来期望在某个地方出现无效的强制转换异常。
Add the strategy to the Strategies collection, not the BuildPlanStrategies.
BuildPlanStrategies is for constructing the objects that will construct the resolved objects. That's not what you're doing - you're just returning the objects directly. I'm surprised you got null, actually - I would have expected an invalid cast exception in there somewhere.