UnityContainer 无法解析类型

发布于 2025-01-06 21:37:36 字数 877 浏览 0 评论 0原文

我在解析 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

思念满溢 2025-01-13 21:37:36

我在 Unity 中注册单例的两种方法是:

_container.RegisterInstance<CommandReaderWriter>(new CommandReaderWriter);

_container.RegisterType<CommandReaderWriter,CommandReaderWriter>(new ContainerControlledLifetimeManager());

两种方法都将 Unity LifeTimeManager 设置为 ContainerControlledLifeTimeManager,这是 Unity 所说的单例。

如果您想精确控制对象的构造方式,请使用 RegisterInstance。第二个选项是我的首选,因为 Unity 会为我完成所有依赖项管理。

The two ways I use to register a singleton in Unity are:

_container.RegisterInstance<CommandReaderWriter>(new CommandReaderWriter);

and

_container.RegisterType<CommandReaderWriter,CommandReaderWriter>(new ContainerControlledLifetimeManager());

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文