使用Autofac的IIndex来解析多个Keyed实例

Eel*_*lco 3 c# autofac

我想以状态和策略模式共存的方式使用 AutoFac。在研究了如何操作之后,我熟悉了 Autofac 的键控/命名注册,并使用被动IIndex方法将其用于我的状态。之后,我研究了策略模式,对我来说,这似乎是使用相同想法的好方法,可以解决IIndex状态和策略问题。我以与状态相同的方式 ( enum) 保存了我的策略选项,并将它们键入DependencyResolver

builder.RegisterType<NewAanvraag>().Keyed<IAanvraagState>(AanvraagState.Nieuw).Keyed<IAanvraagState>(BusinessState.Default);
builder.RegisterType<RareNewAanvraag>().Keyed<IAanvraagState>(AanvraagState.Nieuw).Keyed<IAanvraagState>(BusinessState.Rare);
builder.RegisterType<OpvoerenInformatie>().Keyed<IAanvraagState>(AanvraagState.OpvoerenInformatie).Keyed<IAanvraagState>(BusinessState.Default);
Run Code Online (Sandbox Code Playgroud)

这样,我想使用以动态顺序创建的两个选项,而某些实现可能与默认值相同,而有些则不然。然而,当尝试访问状态和策略时,我得到了 的概念KeyedServiceIndex2 (DelegateActivator),但这两个选项都无法单独解决

private readonly IIndex<AanvraagState, IAanvraagState> _states;
private readonly IIndex<BusinessState, IAanvraagState> _strategyState;

public IAanvraagDto AanvraagDto { get; set; }
private IAanvraagState CurrentState{ get { return _states[AanvraagDto.State];} }
private IAanvraagState CurrentStrategy { get { return _strategyState[AanvraagDto.BusinessState]; } }

public Aanvraag(IIndex<AanvraagState, IAanvraagState> states, IIndex<BusinessState, IAanvraagState> strategyState)
{
    _states = states;
    _strategyState = strategyState;
}

public void Start()
{
    CurrentStrategy.Start(AanvraagDto);
    SetState(AanvraagState.OpvoerenInformatie);
}
Run Code Online (Sandbox Code Playgroud)

当我尝试同时使用两者时,它找不到实现(也尝试过IIndex<BusinessState, IIndex<AanvraagState, IAanvraagState>>):

private readonly IIndex<AanvraagState, IIndex<BusinessState, IAanvraagState>> _states;

public IAanvraagDto AanvraagDto { get; set; }
private IAanvraagState CurrentState { get { return _states[AanvraagDto.State][AanvraagDto.BusinessState]; } }

public Aanvraag(IIndex<AanvraagState, IIndex<BusinessState, IAanvraagState>> states)
{
    _states = states;
}

public void Start()
{
    CurrentState.Start(AanvraagDto);
    SetState(AanvraagState.OpvoerenInformatie);
}
Run Code Online (Sandbox Code Playgroud)

有谁知道如何使用 2 个键控变量来检索网格状结构来解决具体实现?

PS:这是我在 StackOverflow 上提出的第一个问题,因此非常感谢任何建设性的反馈。

Tra*_*lig 5

这种IIndex<K,V>关系实际上仅适用于单维密钥服务。它不适用于多维选择。

您更有可能寻找的是组件元数据,能够将任意数据与注册相关联并根据该数据选择注册。

该文档有一些很好的示例和详细信息,但我将向您展示一个可能与您正在做的事情密切相关的简单示例。

首先,您需要定义一个元数据类。这是跟踪您想要选择组件的“矩阵”的各种“维度”的东西。我将在这里做一些简单的事情 - 两个布尔字段,因此总共只有四种可用元数据组合:

public class ServiceMetadata
{
    public bool ApplicationState { get; set; }
    public bool BusinessState { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我将使用一些非常简单的空服务仅用于说明。你的显然会做更多的事情。注意我有四种服务 - 每种服务对应元数据组合。

// Simple interface defining the "service."
public interface IService { }

// Four different services - one for each
// combination of application and business state
// (e.g., ApplicationState=true, BusinessState=false).
public class FirstService : IService { }
public class SecondService : IService { }
public class ThirdService : IService { }
public class FourthService : IService { }
Run Code Online (Sandbox Code Playgroud)

这是您使用服务的地方。为了更轻松地利用强类型元数据,您需要引用System.ComponentModel.Composition以便能够访问System.Lazy<T, TMetadata>.

public class Consumer
{
    private IEnumerable<Lazy<IService, ServiceMetadata>> _services;

    public Consumer(IEnumerable<Lazy<IService, ServiceMetadata>> services)
    {
        this._services = services;
    }

    public void DoWork(bool applicationState, bool businessState)
    {
        // Select the service using LINQ against the metadata.
        var service =
            this._services
                .First(s =>
                       s.Metadata.ApplicationState == applicationState &&
                       s.Metadata.BusinessState == businessState)
                .Value;

        // Do whatever work you need with the selected service.
        Console.WriteLine("Service = {0}", service.GetType());
    }
}
Run Code Online (Sandbox Code Playgroud)

当您进行注册时,您需要将元数据与组件一起注册,以便它们知道它们属于哪种数据组合。

var builder = new ContainerBuilder();
builder.RegisterType<Consumer>();
builder.RegisterType<FirstService>()
    .As<IService>()
    .WithMetadata<ServiceMetadata>(m => {
        m.For(sm => sm.ApplicationState, false);
        m.For(sm => sm.BusinessState, false);
    });
builder.RegisterType<SecondService>()
    .As<IService>()
    .WithMetadata<ServiceMetadata>(m => {
        m.For(sm => sm.ApplicationState, false);
        m.For(sm => sm.BusinessState, true);
    });
builder.RegisterType<ThirdService>()
    .As<IService>()
    .WithMetadata<ServiceMetadata>(m => {
        m.For(sm => sm.ApplicationState, true);
        m.For(sm => sm.BusinessState, false);
    });
builder.RegisterType<FourthService>()
    .As<IService>()
    .WithMetadata<ServiceMetadata>(m => {
        m.For(sm => sm.ApplicationState, true);
        m.For(sm => sm.BusinessState, true);
    });
var container = builder.Build();
Run Code Online (Sandbox Code Playgroud)

最后,正如您所说,您可以使用您的消费者类别通过“矩阵”获取服务。这段代码:

using(var scope = container.BeginLifetimeScope())
{
    var consumer = scope.Resolve<Consumer>();
    consumer.DoWork(false, false);
    consumer.DoWork(false, true);
    consumer.DoWork(true, false);
    consumer.DoWork(true, true);
}
Run Code Online (Sandbox Code Playgroud)

将在控制台上生成:

Service = FirstService
Service = SecondService
Service = ThirdService
Service = FourthService
Run Code Online (Sandbox Code Playgroud)

同样,您肯定会想查看文档以获取更多详细信息和示例。它将增加说明并帮助您了解可用的其他选项,以便使此操作变得更容易或在您的系统中更好地工作。