繁体   English   中英

在Unity中,如何将命名依赖项与其他依赖项一起注入到构造函数中?

[英]In Unity, how do I inject a named dependency into a constructor with other dependencies?

我有一个具有某些依赖项的服务,但其中之一是命名依赖项。 因此,要配置我的Unity容器以注入它。

我有这样的事情:

在Unity容器中注册类型:

container.RegisterType<IOtherService, Implementation>("SpecificImp);
container.RegisterType<IOtherService, OtherImplementation>("otherImp");

container.RegisterType<IService, Service>(
    new InjectionConstructor(                  // Explicitly specify a constructor
        new ResolvedParameter<IOtherService>("SpecificImp") // Resolve parameter of type IRepository using name "Client"
    )
);

服务:

puclic class Service : IService
{
     private read-only IOtherService _otherService;
     private read-only IworkContext _workContext;

    public Service(
        IOtherService otherService,
        IworkContext workContext)
    {
        _otherService = otherService;
        _workContext = workContext;
    }
}

但是编译器告诉我一个错误,

“实施”没有带有“ IOtherService”参数的构造器。

那么,谁可以配置mi容器以注入正确的实现?

如果要显式指定任何构造函数参数,则需要指定该构造函数的所有参数

container.RegisterType<IService, Service>(
    new InjectionConstructor(                  // Explicitly specify a constructor
        new ResolvedParameter<IOtherService>("SpecificImp"), // Resolve parameter of type IRepository using name "Client"
    new ResolvedParameter<IworkContext>()
)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM