DryIoc - 当 base class 注册了一个键名时解析一个 dervied class

DryIoc - Resolving a dervied class when base class is registered with a key name

尝试在 Prism.Forms (https://github.com/joacar/Prism/tree/pr-517) 中构建对 DryIoc 的支持,但偶然发现了一个我不知道该怎么做的场景。

长话短说,问题归结为:在 Prism.DryIoc.Forms 中创建新应用程序时,创建 PrismApplicationBase 的应用程序子 class 并覆盖某些方法,其中之一是注册类型。

调用时,用户可以注册导航视图

container.RegisterPageForNavigation<MockView>(); 
// Extension method implementation
public static void RegisterPageForNavigation<TPage>(this IContainer container) 
where TPage : Xamarin.Forms.Page
{
    container.Register<TPage>(typeof(TPage).FullName);
}

在导航过程中,class DryIocPageNavigationService 参与并有一个方法可以覆盖 protected Page CreatePage(string name) { ... }

问题来了:此时我们只知道使用 IContainer 解析给定 'name' 的 Page 的实现。

protected Page CreatePage(string name) 
{ 
    // Always returns null
    return _container.Resolve<Page>(name, IfUnresolved.DefaultOrNull);
}

但是,如果以这种方式实现扩展方法

 public static void RegisterPageForNavigation<TPage>(this IContainer container)
 where TPage : Xamarin.Forms.Page, new()
 {
     container.Register<Page>(made: 
         Made.Of(() => new TPage()),serviceKey:typeof(TPage).FullName);
 }

页面已解决。然而,这将 TPage 限制为具有默认的空构造函数(或进行一些 clever/unwanted 黑客攻击)

嗯,短篇小说够长了吧:)

此致

而不是注册使用 RegisterMany:

Container.RegisterMany<TPage>(
     serviceKey: whatever);

这将使用 TPage 提供的多种服务类型注册单个工厂:TPage 本身、基本页面 class 和接口(如果有)。

// works
Container.Resolve<Page>(
     serviceKey: whatever);