1

I've started a project usinjg MS Unity as my IOC container and have two questions regarding overriding parameters.

public interface ITab
{
   bool AllowVisible {get;set;}
}

class Tab : ITab
{
  IViewModel vm;

  public Tab(IViewModel vm)
  {
    this.vm = vm; 
  }

  public bool allowVisible = false;

  public bool AllowVisible
  {
    get{ return allowVisible};
    set{ allowVisible = vlaue};
  }
} 

public interface IViewModule
{
  string Name;
}

public class ViewModel
{
  public string Name;
}

1) How do i set up the Tab type in unity so that i can pass in true or false to the AllowVisible property as a paramater? I dont want to have to add the additional line of tab.AllowVisible = true; as in the case below

void Main()
{
   ITab tab = unityContainer.RegisterType<ITab, Tab>(); 
   tab.AllowVisible = true;
}

2) If i already have an instance of the ViewModel, such as vm in the case below, how do i make the container resolve the Tab object while passing in the vm object into its constructor? Currently when i resolve for the tab object, the container creates another instance of the ViewModel. I want the vm instance to get used as the tab objects viewmodel?

void Main()
{
    unityContainer.RegisterType<IViewModel, ViewModel>();
    unityContainer.RegisterType<ITab, Tab>();

   ViewModel vm = unityContainer.Resolve<IViewModel>();   
   ITab tab = unityContainer.RegisterType<ITab, Tab>(); 
}
caa
  • 406
  • 1
  • 8
  • 16

1 Answers1

3

If you automatically want to assign a value to the AllowVisible property of your ITab implementation then you can use the InjectionProperty type provided by Unity.

You can do this in a fluent way, for example:

IUnityContainer myContainer = new UnityContainer();
myContainer.Configure<InjectedMembers>()
           .ConfigureInjectionFor<MyObject>(
               new InjectionProperty("MyProperty"),
               new InjectionProperty("MyStringProperty", "SomeText"))
);

A bit more concrete:

container.RegisterType<ITab, Tab>();
container.RegisterType<ITab, Tab>(
    new InjectionProperty("AllowVisible", true) 
);

For more information on how to inject constructor parameters, property values...etc, check out:

http://msdn.microsoft.com/en-us/library/ff650036.aspx

As for the second part of you question, you must pass constructor parameters (IViewModel) to Unity's Resolve(...) method when you resolve an implementation for an ITab.

This question has been asked before on SO, check out:

Can I pass constructor parameters to Unity's Resolve() method?

For completeness' sake:

var viewModel = container.Resolve<IViewModel>();
container.Resolve<ITab>(new ParameterOverrides<Tab> { { "vm", viewModel} });"
Community
  • 1
  • 1
Christophe Geers
  • 8,564
  • 3
  • 37
  • 53