Unity 依赖注入(构造函数或属性)
我在项目中使用 Unity 一段时间了。我有一个单例容器,用于注册类型和/或实例,然后进行解析。
今天我想通过使用属性或构造函数注入来自动化一些实例化。
我从 Logger 类开始。在应用程序启动中,我有这样的代码:
RegisterType<Logger, Logger>();
比在我的 ViewModel 中
[Dependency]
public Logger MyLogger {
get;
set;
}
,这里是我如何实例化具有此属性的视图模型(在 MainWindow.xaml.cs 中),
private void InitializeViewModel() {
_vm = new MainViewModel(MainGrid);
...
MyContainer.GetInstance().Container.RegisterInstance<MainViewModel>(_vm);
我无法让 [属性注入器] 工作。属性注入是否需要与构造函数配对?我已经在使用带有一些参数的构造函数。
I've been using Unity for some time in my project. I have a singleton Container which I use to register types and/or instances, and later resolve.
today i wanted to automate some of the instantiation by using property or constructor injection.
I started with Logger class. In Application start i have this code:
RegisterType<Logger, Logger>();
than in my ViewModel
[Dependency]
public Logger MyLogger {
get;
set;
}
here is how i instantiate the viewmodel that has this property (in MainWindow.xaml.cs)
private void InitializeViewModel() {
_vm = new MainViewModel(MainGrid);
...
MyContainer.GetInstance().Container.RegisterInstance<MainViewModel>(_vm);
I can't get that [property injector] to work. Does property injection NEED to be paired up with a constructor? I am already using a constructor that has some parameters..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你的例子有问题。如果您希望将
Logger
注入到MainViewModel
中,则必须让容器为您创建MainViewModel
。但是,在您的代码中,您是自己创建的。在我看来,它应该是:
或者至少
Something's wrong in your example. If you want the
Logger
to be injected intoMainViewModel
, you'd have to let the container create theMainViewModel
for you.However, in your code you are creating it by yourself. As I look at it, it should be:
or at least
您需要让 Unity 容器来创建视图模型,而不是使用 new MainViewModel() 来创建视图模型。
然后您可以使用 Container.Resolve() 来获取以前称为
_vm
的单例。注意:
ContainerControlledLifetimeManager
部分告诉 Unity 仅创建 MainViewModel 的单个实例并为所有内容返回它。Instead of using
new MainViewModel()
to create the viewmodel, you need to have your Unity Container do the creation.And then you can use
Container.Resolve<MainViewModel>()
to get your singleton formerly known as_vm
.Note: The
ContainerControlledLifetimeManager
part tells Unity to only create a single instance of MainViewModel and return it for everything.