Register type with Unity to use a constructor requiring an array of parameters

Given the following constructor signature:

public MyClass(Class1 arg1, params Class2[] arg2) 

How can I register MyClass with Unity passing in specific named types using InjectionConstructor.

I tried the following:

 unityContainer.RegisterType<IMyClass, MyClass>(new InjectionConstructor(typeof(Class1), new ResolvedParameter<IClass2>("name1"), new ResolvedParameter<IClass2>("name2"))) 

but get an exception saying that there is no constructor with a signature:

 public MyClass(Class1 arg1, Class2 arg2, Class2 arg3) 

I had a problem overloading the MyClass constructor. Is there a way to do this without overloading the constructor?

+6
source share
2 answers

Why are you trying to use the InjectionConstructor in the first place? Unity knows how to handle arrays out of the box.

The params is just syntactic sugar for the compiler. Under the cover of args2 is just a simple array.

 [TestMethod] public void TestMethod1() { var container = new UnityContainer(); // if you absolutely have to use an InjectionConstructor this should do the trick // container.RegisterType<IMyClass, MyClass>( // new InjectionConstructor(typeof(Class1), typeof(Class2[]))); container.RegisterType<IMyClass, MyClass>( new InjectionConstructor(typeof(Class1), typeof(Class2[]))); container.RegisterType<Class2>("1"); container.RegisterType<Class2>("2"); container.RegisterType<Class2>("3"); var myClass = container.Resolve<IMyClass>() as MyClass; Assert.IsNotNull(myClass); Assert.IsNotNull(myClass.Arg2); Assert.AreEqual(3, myClass.Arg2.Length); } interface IMyClass { } class MyClass : IMyClass { public Class1 Arg1 { get; set; } public Class2[] Arg2 { get; set; } public MyClass(Class1 arg1, params Class2[] arg2) { Arg1 = arg1; Arg2 = arg2; } } class Class1 { } class Class2 { } 

Update

If you use only some of these registrations, you will have to use ResolvedArrayParameter .

 container.RegisterType<IMyClass, MyClass>( new InjectionConstructor( typeof(Class1), new ResolvedArrayParameter<Class2>( new ResolvedParameter<Class2>("1"), new ResolvedParameter<Class2>("2")))); 

Brrr! This is super ugly, but it should solve your problem.

+6
source

Since it seems that instances of the Class2 class are simply listed directly, is it possible that explicitly setting them to an array (and, therefore, explicitly matching the signature of the constructor of Class1, Class2[] ) will work:

 unityContainer.RegisterType<IMyClass, MyClass>(new InjectionConstructor(typeof(Class1), new Class2[]{new ResolvedParameter<IClass2>("name1"), new ResolvedParameter<IClass2>("name2")})) 
+1
source

All Articles