尝试在 Prism.Forms ( https://github.com/joacar/Prism/tree/pr-517 ) 中构建对 DryIoc 的支持,并偶然发现了一个我无法弄清楚该怎么做的场景。
长话短说,问题归结为:在 Prism.DryIoc.Forms 中创建新应用程序时,创建 PrismApplicationBase 的应用程序子类并覆盖某些方法,其中之一是 RegisterTypes。
当被调用时,用户可以注册一个导航 View
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);
}
在导航过程中,类 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
具有默认的空构造函数(或者做一些聪明的/不需要的黑客攻击)
嗯,短篇小说会变得很长 :)
最好的问候
最佳答案
而不是注册使用 RegisterMany :
Container.RegisterMany<TPage>(
serviceKey: whatever);
这将使用 TPage 提供的多种服务类型注册单个工厂:TPage 本身、基 Page 类和接口(interface)(如果有)。
// works
Container.Resolve<Page>(
serviceKey: whatever);
关于c# - DryIoc - 在使用键名注册基类时解析派生类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36272016/