寻求如何告诉 Autofac 按名称注入哪个服务的示例

Seeking example of how to tell Autofac which service to inject by name

我需要一个像 [WithNamed("x")] 这样的属性,它会告诉 Autofac 如何为每个 'service' 注入正确的参数,如图所示。

要注入两个版本的FlagXCtlr的构造函数:

public CoupDo(
        [WithName("FLAG6")]ItemUserFlagCtrl Flag6Ctlr,
        [WithName("FLAG5")]ItemUserFlagCtrl Flag5Ctlr)
{
...
}

注册完成:

builder.RegisterType<ItemUserFlagCtrl>()
       .Named<IItemUserFlagCtrl>("FLAG6")
       .WithParameter("userFlagParm", "FLAG6")
       .SingleInstance();

builder.RegisterType<ItemUserFlagCtrl>()
       .Named<IItemUserFlagCtrl>("FLAG5")
       .WithParameter("userFlagParm", "FLAG5")
       .SingleInstance();  

而这个服务的构造函数是这样的:

public ItemUserFlagCtrl(string userFlagParm)  
{
   switch (userFlagParm)   
   {

好像是"WithKey"!

这看起来很有帮助,我如何获得 "WithKey" 属性?

我添加了下面显示的这两个 'using' 语句,但无济于事。作为参考我有Autofac.dll,Autofac.Configuration.dll,还有两个,我接下来会尝试。

using Autofac;         
using Autofac.Features.Metadata; 

错误:

public CouponSorter(
    [error:**WithKey**("FLAG6")]ItemUserFlagCtrl Flag6Ctlr,
    [error:**WithKey**("FLAG5")]ItemUserFlagCtrl Flag5Ctlr)

文档说:

Named services are simply keyed services that use a string as a key

Named and Keyed Services

这意味着你可以使用带有字符串参数的WithKey属性来做你想做的事:

public CoupDo(
        [WithKey("FLAG6")]ItemUserFlagCtrl Flag6Ctlr,
        [WithKey("FLAG5")]ItemUserFlagCtrl Flag5Ctlr)
{
...
}

WithKeyAttributeAutofac.Extras.Attributed 命名空间的 Autofac.Extras.Attributed nuget 包中定义。

另一种解决方案是使用 IIndex<TKey, TValue> 类型

public CoupDo(IIndex<String, ItemUserFlagCtrl> flagControls) 
{
    ItemUserFlagCtrl flag6Ctlr = flagControls["FLAG6"]; 
    // or 
    ItemUserFlagCtrl flag6Ctlr = null; 
    if(!flagControls.TryGetValue("FLAG6"), out flag6Ctrl))
    {
        // do whatever you want if you don't have a FLAG6 named control
    }
    ...
}