Ignacio Soler Garcia
Ignacio Soler Garcia

Reputation: 21855

How do I configure Unity to share an instance in two constructors?

Say I have the following classes / constructors:

public class Model {} // Parameterless constructor here
public class Controller { public Controller(Model model) {} }
public class ViewModel { public ViewModel(Model model) {} }

I want to have a factory that creates one model, one controller and one viewmodel using the same model instance on the Controller and the ViewModel.

How can I configure Unity to use it on the factory so that the same instance is used in both constructors?

EDIT:

Every time I want to create a ViewModel I want to create a Controller and a Model. So 1VM = 1C = 1M and the model is shared between the VM and the C.

Upvotes: 3

Views: 108

Answers (1)

TTat
TTat

Reputation: 1496

It's not clear how your View Model and Control are related, so it's a little hard to see how resolving one will resolve the other. Something you can try is a factory with two out parameters and Injection Constructor.

// However you decide to setup your factory method
public static void CreateViewModelAndController(
    out ViewModel viewModel, 
    out Controller controller, 
    IUnityContainer unityContainer)
{
    Model model = unityContainer.Resolve<Model>();
    viewModel = unityContainer.Resolve<ViewModel>(new InjectionConstructor(model));
    controller = unityContainer.Resolve<Controller>(new InjectionConstructor(model));
}

Upvotes: 2

Related Questions