Chase Florell
Chase Florell

Reputation: 47417

Resolving DryIoc serviceKey implementations using a factory class

I'm attempting to build a Factory class to return a given service implementation based on an Enum service key.

My registrations:

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));
}

The factory class is intended to resolve all of the Pages within the constructor and store them in a backing field for future use.

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;
}

The problem is that when I land at the line _pages = pages, the value being injected has Count = 0 and I'm not sure what I'm missing.

What do I need to do to implement this pattern in DryIoc?

Upvotes: 1

Views: 399

Answers (1)

dadhi
dadhi

Reputation: 4950

From the first glance , you are registering your pages via implementation type TPage but resolving the dictionary of the Page. You need to change your registrations to container.Register<Page, TPage>(...).

Upvotes: 1

Related Questions