【问题标题】:Dependency Injection non interface constructor依赖注入非接口构造函数
【发布时间】:2023-03-08 18:14:01
【问题描述】:

我正在使用 Unity 并且想要执行以下操作:我基本上想将值类型传递给基本构造函数。

这是一个典型的接口L

public interface Irepo
{

void test();
}

这里是实现的类,我希望也能在构造函数中注入一个非接口。这可能吗?

public class Repo : baseRepo, Irepo
{
public Repo(IOther other, string username) : base(username)
{}
public void test(){}
}

这是这个统一配置:

container.RegisterType<Irepo, Repo>();
container.RegisterType<IOther , Other>();

我试过这个,但它说 Repo 没有接受字符串的参数。有人有什么想法吗?

container.RegisterType<Irepo, Repo>("user", new InjectionConstructor("user"));

【问题讨论】:

    标签: c# dependency-injection


    【解决方案1】:

    如果您提供 InjectionConstructor 来为构造函数提供参数,那么您需要提供所有参数,即使它们本身是已注册的接口。

    container.RegisterType<Irepo, Repo>("user", new InjectionConstructor(
        container.Resolve<IOther>(),
        "user"
    ));
    

    【讨论】:

      猜你喜欢
      • 2011-02-02
      • 1970-01-01
      • 2019-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多