创建一个后备容器/解析器DryIoc

时间:2016-03-25 17:34:22

标签: dryioc

目前正致力于创建一个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,因为我已经读过它应该是最快的

1 个答案:

答案 0 :(得分:2)

更新回答:

您可以直接使用WithUnknownServiceResolvers返回DelegateFactory:

var c = new Container(Rules.Default.WithUnknownServiceResolvers(request =>
    new DelegateFactory(_ => GetFromDependencyService(request.ServiceType))));

不需要为此实现IContainer。

我认为可以通过将ExpressionFactory替换为ExpressionFactory来优化性能。但我需要一些时间来实现这个想法。