用于多参数构造函数的Unity InjectionConstructor仅覆盖单个构造函数

Ale*_*sev 42 c# unity-container

我有一个像这样的构造函数的类:

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

    }
}
Run Code Online (Sandbox Code Playgroud)

我想在Unity中注册Bar并为文本提供值:

unity.RegisterType<Bar, Bar>(new InjectionConstructor("123"));
Run Code Online (Sandbox Code Playgroud)

但是我不能这样做,因为Bar没有单个参数构造函数.

有没有办法为文本提供一个值而不指定所有其他参数ResolvedParameter<IFooN>等.我真的不喜欢它,很多代码,每次我更改Bar的构造函数我需要添加另一个ResolvedParameter

Seb*_*ber 44

Unity无法开箱即用.你能做的最好的事情是:

container.RegisterType<Bar>(
    new InjectionConstructor(
        typeof(IFoo), typeof(IFoo2), typeof(IFoo3), typeof(IFooN), "123"));
Run Code Online (Sandbox Code Playgroud)

或者您可以使用TecX项目SmartConstructor提供的.这篇博文描述了一些背景知识.

注册将如下所示:

container.RegisterType<Bar>(new SmartConstructor("text", "123"));
Run Code Online (Sandbox Code Playgroud)

  • 如果需要传递null而不是"123",则需要使用新的InjectionParameter <string>(null) (2认同)