Im new with Microsoft Unity Container, so my question may be trivial. I got to register and resolve instances for classes with only one parameterless constructor. Now I wish to learn how to register and resolve a class with a simple constructor. Here is my class.
public class MyClass
{
private string a1;
public string A1
{
get { return a1; }
set { a1 = value; }
}
private int a2;
public int A2
{
get { return a2; }
set { a2 = value; }
}
public MyClass()
{ this.a1 = "aaaaa";
this.a2 = 1;
}
public MyClass(string a1,int a2)
{
this.a1 = a1;
this.a2 = a2;
}
}
I got to register and resolve the MyClass() constructor; then, I tried to register the second
//App.xaml.cs
container = new UnityContainer();
container.RegisterType<MainView>();
............
container.RegisterType<string>("A1");
container.RegisterType<int>("A2");
container.RegisterType<MyClass>("MyClassConstructor",new InjectionConstructor(new ResolvedParameter<string>("A1"),new ResolvedParameter<int>("A2")));
//NavigationService.cs, create an instance of MyClass("mystring",100) and bind it to a window
public Window ShowMainView()
{
var window = Container.Resolve<MainView>();
MyClass myClass = Container.Resolve<MyClass>("MyClassConstructor", new ParameterOverrides { { "A1", "mystring" }, { "A2", 100 } });
window.DataContext = myClass ;
window.Show();
return window;
}
when the container tries to create the MyClass instance, I got this error:
Resolution of the dependency failed, type = "MySolution.MyProject.ViewModels.MyClass", name = "MyClassConstructor". Exception occurred while: while resolving.
Exception is: InvalidOperationException - The type String cannot be constructed. You must configure the container to supply this value.
At the time of the exception, the container was:
Resolving MySolution.MyProject.ViewModels.MyClass,MyClassConstructor Resolving parameter "a1" of constructor MySolution.MyProject.ViewModels.MyClass(System.String a1, System.Int32 a2) Resolving System.String,A1
please, help me to understand how it works. thanks