Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity InjectionConstructor for multiparam constructor overriding only single one

I have a class with constructor like this:

public class Bar {     public Bar(IFoo foo, IFoo2 foo2, IFoo3 foo3, IFooN fooN, String text)     {      } } 

I want to register Bar in Unity and provide a value for text:

unity.RegisterType<Bar, Bar>(new InjectionConstructor("123")); 

However I can't do this because there is no single parameter constructor for Bar.

Is there a way to provide a value for text without specifying all other parameters as ResolvedParameter<IFooN> etc.. I really don't like it, lot's of code, and every time I change a constructor of Bar I need to add another ResolvedParameter

like image 723
Alex Burtsev Avatar asked Aug 08 '12 14:08

Alex Burtsev


1 Answers

Unity can't do this out of the box. The best you can do is:

container.RegisterType<Bar>(     new InjectionConstructor(         typeof(IFoo), typeof(IFoo2), typeof(IFoo3), typeof(IFooN), "123")); 

Or you can use the SmartConstructor provided by the TecX project. This blog post describes some background.

Registration would look like this:

container.RegisterType<Bar>(new SmartConstructor("text", "123")); 
like image 151
Sebastian Weber Avatar answered Sep 17 '22 16:09

Sebastian Weber