UnityContainer 无法解析类型
我在解析 UnityContainer 中注册的类型时遇到问题。在我的引导程序中,我重写了ConfigureContainer方法。现在这个方法看起来像这样
protected override void ConfigureContainer()
{
base.ConfigureContainer();
RegisterTypeIfMissing(typeof(IView<ShellViewModel>), typeof(Shell), false);
RegisterTypeIfMissing(typeof(CommandReaderWriter), typeof(CommandReaderWriter), true);
}
然后在函数 CreateShell (也在引导程序中)我想获取 CommandReaderWriter 类型的实例,所以我这样做了
var raeder = Container.TryResolve<CommandReaderWriter>();
,不幸的是它返回空值。我也尝试过
var anotherReader = Container.TryResolve(typeof (CommandReaderWriter));
,但没有成功。然而,有趣的是返回 true 的事实
var isRegistered = Container.IsTypeRegistered(typeof (CommandReaderWriter));
。
那么在 UnityContainer 中注册 singletone 的正确方法是什么?
I have a problem with resolving a type which is registered in UnityContainer. In my bootstraper I overrode ConfigureContainer method. Now this method looks like this
protected override void ConfigureContainer()
{
base.ConfigureContainer();
RegisterTypeIfMissing(typeof(IView<ShellViewModel>), typeof(Shell), false);
RegisterTypeIfMissing(typeof(CommandReaderWriter), typeof(CommandReaderWriter), true);
}
Then in function CreateShell (also in bootstraper) I want to get the instance of type CommandReaderWriter so I did this
var raeder = Container.TryResolve<CommandReaderWriter>();
unfortunatelly this returns null value. I also tried
var anotherReader = Container.TryResolve(typeof (CommandReaderWriter));
but it didn't do a trick. However, interesting is the fact that
var isRegistered = Container.IsTypeRegistered(typeof (CommandReaderWriter));
returns true.
so what is approperiate way to register singletone in UnityContainer ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我在 Unity 中注册单例的两种方法是:
这
两种方法都将 Unity LifeTimeManager 设置为 ContainerControlledLifeTimeManager,这是 Unity 所说的单例。
如果您想精确控制对象的构造方式,请使用 RegisterInstance。第二个选项是我的首选,因为 Unity 会为我完成所有依赖项管理。
The two ways I use to register a singleton in Unity are:
and
Both these methods set the Unity LifeTimeManager to be a ContainerControlledLifeTimeManager, which is Unity-speak for a singleton.
If you want to control exactly how the object is constructed use RegisterInstance. The second option is my preferred one because Unity then does all the dependency management for me.