2
votes

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..

2
How are you creating the object that contains the Logger property? - Joachim Isaksson
That's what I suspected, see the answer from @WiktorZychia :) - Joachim Isaksson

2 Answers

2
votes

Something's wrong in your example. If you want the Logger to be injected into MainViewModel, you'd have to let the container create the MainViewModel for you.

However, in your code you are creating it by yourself. As I look at it, it should be:

_vm = Container.Resolve<MainViewModel>();

or at least

_vm = new MainViewModel();
Container.BuildUp( _vm ); 
1
votes

Instead of using new MainViewModel() to create the viewmodel, you need to have your Unity Container do the creation.

Container.RegisterType<MainViewModel>(
     new ContainerControlledLifetimeManager(),
     new InjectConstructor(MainGrid)
   );

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.