Unity InjectionConstructor for multiparam constructor overriding only single one

Alex Burtsev picture Alex Burtsev · Aug 8, 2012 · Viewed 23.8k times · Source

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

Answer

Sebastian Weber picture Sebastian Weber · Aug 8, 2012

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"));