目前正在创建一个 Prism.DryIoc.Forms 项目以尝试 DryIoc(第一次!)。
在 Xamarin.Forms 中有一个本机 DependencyService 并提供一种迁移到使用 Prism 的好方法,我想将其添加为备用容器,以防无法从主容器解析请求的服务类型。
当前,我创建了一个FallbackContainer
并传递了实例,IContainer
并覆盖了方法IResolver
并将其余IContainer
调用委托给创建期间传递的实例。
所以在创建和配置默认容器之后,然后执行
Container = CreateContainer();
ConfigureContainer();
Container.Rules.WithFallbackContainer(new DependencyServiceContainer(Container));
这是首选方法还是有什么方法可以附加默认值IResolver
?
当前实施
public class FallbackDependencyServiceContainer : IContainer
{
private readonly IContainer container;
public FallbackDependencyServiceContainer(IContainer container)
{
this.container = container;
}
public object Resolve(Type serviceType, bool ifUnresolvedReturnDefault)
{
return ResolveFromDependencyService(serviceType);
}
public object Resolve(Type serviceType, object serviceKey, bool ifUnresolvedReturnDefault,
Type requiredServiceType,
RequestInfo preResolveParent, IScope scope)
{
return ResolveFromDependencyService(serviceType);
}
public IEnumerable<object> ResolveMany(Type serviceType, object serviceKey, Type requiredServiceType,
object compositeParentKey,
Type compositeParentRequiredType, RequestInfo preResolveParent, IScope scope)
{
return new[] { ResolveFromDependencyService(serviceType) };
}
private static object ResolveFromDependencyService(Type targetType)
{
if (!targetType.GetTypeInfo().IsInterface)
{
return null;
}
var method = typeof(DependencyService).GetTypeInfo().GetDeclaredMethod("Get");
var genericMethod = method.MakeGenericMethod(targetType);
return genericMethod.Invoke(null, new object[] { DependencyFetchTarget.GlobalInstance });
}
....
}
感谢并期待测试 DryIoc,因为我读过它应该是最快的