Search code examples
dependency-injectionprismdryioc

DI - resolving instance using parameter (Prism using DryIoc)


I've been searching over the web how could I resolve instance using Prism DryIOC that uses parameter during runtime, but to luck yet.

For example, I have a class:

internal sealed class ItemInfoHelper : IItemInfoHelper
{
    //ctor
     public ItemInfoHelper(Item item) {...}
     public string GetSomething() {...}
}

And in registering service I need to register it.

protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
    containerRegistry.Register<IItemInfoHelper, ItemInfoHelper>();
}

If I do this, when I resolve it somewhere like:

var helperInstance = container.Resolve<IItemInfoHelper>();

it will be obviously resolved using empty Item (using default Item constructor). I have seen a lot of examples that register instances using some parameters that are known at compile time. But the case is that I would like to resolve instance being initialized dynamically using Item that would be a different one in different places (i.e. known at runtime only).

Is there a way to register/resolve it using such behavior if I use Prism + DryIoc? Thanks in advance.


Solution

  • The simplest type-safe way to do so is to resolve the function of item:

    var getHelperInstance = container.Resolve<Func<Item, IItemInfoHelper>>();
    var helperInstance = getHelperInstance(myItem);