Share object in container

May 7, 2010 at 9:08 AM

Hello,

I have a questions.  I have existing object which i want to share among view models inside container. The code is like:

 

// in App.xaml.cs
container.RegisterInstance<ISharedObject>(sharedObject);

var firstWindow = container.Resolve<FirstWindow>();

var secondWindow = container.Resolve<SecondWindow>();

// in FirstWindow.xaml.cs
 private FirstViewModel firstViewModel;

[Dependency]
 public FirstViewModel FirstViewModelInst
 {
       get { return firstViewModel; }
       set
            {
                firstViewModel = value;
                DataContext = value;
            }
}

// in SecondWindow.xaml.cs
 private SecondViewModel secondViewModel;

[Dependency]
 public SecondViewModel SecondViewModelInst
 {
       get { return secondViewModel; }
       set
            {
                secondViewModel = value;
                DataContext = value;
            }
}

// in FirstViewModel.cs
private ShareObject sharedObject;

public SharedObject ShareObjectInst
{
      get { return sharedObject; }
      set { sharedObject = value; }
}

public FirstViewModel([Dependency] SharedObject sharedObject)
{
            this.sharedObject = sharedObject;
            sharedObject.Prop = something;
}

// in SecondViewModel.cs
private ShareObject sharedObject;

public SharedObject ShareObjectInst
{
      get { return sharedObject; }
      set { sharedObject = value; }
}

public SecondViewModel([Dependency] SharedObject sharedObject)
{
            this.sharedObject = sharedObject;
}



The problem is, that sharedObject in SecondViewModel is not affected by the change in FirstViewModel.

What am I missing?

Thanks Peter

 

May 7, 2010 at 3:31 PM

You registered the instance as ISharedObject, but your dependencies are on SharedObject. Two different types. Since there's no registration for SharedObject, it uses the default behavior and creates a new one each time.

 

May 12, 2010 at 10:16 AM

You are right. It works now. Thanks.