【问题标题】:Resolving DryIoc serviceKey implementations using a factory class使用工厂类解析 DryIoc serviceKey 实现
【发布时间】:2020-06-07 23:34:56
【问题描述】:

我正在尝试构建一个 Factory 类以基于 Enum 服务密钥返回给定的服务实现。

我的注册:

private static void RegisterPageMap(IRegistrator container)
{
    RegisterPage<SchedulePage>(container, PageKey.Schedule);
    RegisterPage<AccountsPage>(container, PageKey.Accounts);
    RegisterPage<AccountDetailsPage>(container, PageKey.AccountDetails, Reuse.Transient);
    // and more
}

private static void RegisterPage<TPage>(IRegistrator builder, PageKey key) where TPage : Page => RegisterPage<TPage>(builder, key, Reuse.Singleton);

private static void RegisterPage<TPage>(IRegistrator builder, PageKey key, IReuse reuse) where TPage : Page
{
    builder.Register<TPage>(reuse,
                            serviceKey: key,
                            setup: reuse == Reuse.Singleton
                                       ? null
                                       : Setup.With(openResolutionScope: true,
                                                    allowDisposableTransient: true));
}

工厂类旨在解析构造函数中的所有页面并将它们存储在支持字段中以供将来使用。

public sealed class PageFactory : IPageFactory
{
    /// <summary>
    /// DryIoc will resolve all keyed pages into the constructor in the format of a <see cref="KeyValuePair{PageKey, Page}"/>
    /// </summary>
    public PageFactory(KeyValuePair<PageKey, Page>[] pages) => _pages = pages;

    /// <inheritdoc cref="IPageFactory"/>
    public Page GetPageForKey(PageKey key) =>
        _pages.First(x => x.Key == key)
              .Value;

    private readonly KeyValuePair<PageKey, Page>[] _pages;
}

问题是当我到达_pages = pages 行时,注入的值是Count = 0,我不确定我错过了什么。

我需要做什么才能在 DryIoc 中实现这个模式?

【问题讨论】:

    标签: dryioc


    【解决方案1】:

    乍一看,您正在通过实现类型TPage 注册您的页面,但解析Page 的字典。 您需要将您的注册信息更改为container.Register&lt;Page, TPage&gt;(...)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-27
      • 1970-01-01
      相关资源
      最近更新 更多