示例#1
0
        public T Resolve <T>(bool shouldThrowResolveException = false, params OverrideParameter[] overrides)
        {
            var parameterOverrides = new ResolverOverride[overrides.Length];

            for (var i = 0; i < overrides.Length; i++)
            {
                parameterOverrides[i] = new ParameterOverride(overrides[i].ParameterName, overrides[i].ParameterValue);
            }

            T result = default;

            try
            {
                result = _container.Resolve <T>(parameterOverrides);
            }
            catch (Exception ex)
            {
                if (shouldThrowResolveException)
                {
                    throw;
                }
            }

            return(result);
        }
示例#2
0
        public static T GetBusinessInstance <T>(params KeyValuePair <string, object>[] ParamsBatch)
        {
            T BusinessInstance = default(T);

            IUnityContainer container = new UnityContainer();

            container.AddNewExtension <Interception>();

            if (ParamsBatch.Count() > 0)
            {
                container.RegisterType(typeof(T), new Interceptor <TransparentProxyInterceptor>(), new InterceptionBehavior <BusinessServiceBehavior>());

                var ResolverOverrideBatch = new ResolverOverride[ParamsBatch.Count()];
                for (int i = 0; i < ParamsBatch.Count(); i++)
                {
                    ResolverOverrideBatch[i] = new ParameterOverride(ParamsBatch[i].Key, ParamsBatch[i].Value);
                }
                BusinessInstance = container.Resolve <T>(ResolverOverrideBatch);
            }
            else
            {
                container.RegisterType(typeof(T), new Interceptor <TransparentProxyInterceptor>(), new InterceptionBehavior <BusinessServiceBehavior>(), new InjectionConstructor());
                BusinessInstance = UnityContainerExtensions.Resolve <T>(container);
            }

            return(BusinessInstance);
        }
示例#3
0
        public override ResolverOverride[] ExtractResolverOverrides(IBuilderContext context)
        {
            // this method is tightly coupled to the implementation of IBuilderContext. It assumes that the
            // class BuilderContext is used and that a field of type CompositeResolverOverride named 'resolverOverrides'
            // exists in that class
            ResolverOverride[] resolverOverrides = new ResolverOverride[0];

            if (!(context is BuilderContext))
            {
                return(resolverOverrides);
            }

            FieldInfo field = typeof(BuilderContext).GetField(
                FieldNames.ResolverOverrides, BindingFlags.Instance | BindingFlags.NonPublic);

            if (field == null)
            {
                return(resolverOverrides);
            }

            var overrides = field.GetValue(context) as IEnumerable <ResolverOverride>;

            if (overrides != null)
            {
                resolverOverrides = overrides.ToArray();
            }

            return(resolverOverrides);
        }
        public void EqualsTest(ResolverOverride resolver)
        {
            // Act
            var result = resolver.Equals((object)resolver);

            // Validate
            Assert.IsTrue(result);
        }
示例#5
0
        /// <summary>
        /// Create an instance of <see cref="TypeBasedOverride"/>
        /// </summary>
        /// <param name="targetType">Type to check for.</param>
        /// <param name="innerOverride">Inner override to check after type matches.</param>
        public TypeBasedOverride(Type targetType, ResolverOverride innerOverride)
        {
            Guard.ArgumentNotNull(targetType, "targetType");
            Guard.ArgumentNotNull(innerOverride, "innerOverride");

            this.targetType = targetType;
            this.innerOverride = innerOverride;
        }
        public void EqualsOperatorTest(ResolverOverride resolver)
        {
            // Validate
            Assert.IsFalse(null == resolver);
            Assert.IsFalse(resolver == null);

            Assert.IsTrue(null != resolver);
            Assert.IsTrue(resolver != null);
        }
示例#7
0
        public static void AddResolverOverrides(ref BuilderContext ctx, ResolverOverride theOverride)
        {
            var newOverrides = ctx.Overrides;

            newOverrides = newOverrides == null
                ? new ResolverOverride[] { theOverride }
                : newOverrides.Concat(new[] { theOverride }).ToArray();

            ctx.Overrides = newOverrides;
        }
示例#8
0
        public T Resolve <T>(string key, params ResolverParameter[] parameters)
        {
            var resolverOverrides = new ResolverOverride[parameters.Length];

            for (var i = 0; i < parameters.Length; i++)
            {
                resolverOverrides[i] = new ParameterOverride(parameters[i].ParameterName, parameters[i].ParameterValue);
            }
            return(_container.Resolve <T>(key, resolverOverrides));
        }
        private ResolverOverride[] ConvertToUnityArguments(IReadOnlyList <IConstructorArgument> parameterArguments)
        {
            var parameterOverrides = new ResolverOverride[parameterArguments.Count];

            for (int i = 0; i < parameterArguments.Count; i++)
            {
                parameterOverrides[i] = new ParameterOverride(parameterArguments[i].Name, parameterArguments[i].Value);
            }

            return(parameterOverrides);
        }
示例#10
0
        private Page GetPage(PageKey pageKey, IDictionary <string, object> parameters = null)
        {
            Page page;

            ResolverOverride[] resolverOverrides = null;
            if (parameters != null && parameters.Count() > 0)
            {
                resolverOverrides = new ResolverOverride[parameters.Count()];
                for (int i = 0; i < parameters.Count(); i++)
                {
                    var dictionaryItem = parameters.ElementAt(i);
                    resolverOverrides[i] = new ParameterOverride(dictionaryItem.Key, dictionaryItem.Value);
                }
            }

            switch (pageKey)
            {
            case PageKey.Login:
                page = (Page)ContainerManager.Container.Resolve(typeof(Login), typeof(Login).ToString());
                break;

            case PageKey.Dashboard:
                page = (Page)ContainerManager.Container.Resolve(typeof(Dashboard), typeof(Dashboard).ToString());
                break;

            case PageKey.TrainingReport:
                page = (Page)ContainerManager.Container.Resolve(typeof(TrainingReport), typeof(TrainingReport).ToString());
                break;

            case PageKey.Admin:
                page = (Page)ContainerManager.Container.Resolve(typeof(Admin), typeof(Admin).ToString());
                break;

            case PageKey.ManageDriver:
                page = (Page)ContainerManager.Container.Resolve(typeof(ManageDriver), typeof(ManageDriver).ToString());
                break;

            case PageKey.System:
                page = (Page)ContainerManager.Container.Resolve(typeof(SystemView), typeof(SystemView).ToString());
                break;

            default:
                throw new ArgumentException(
                          $"No such page: {pageKey}. Did you forgot to register your view in Bootstrapper?", nameof(pageKey));
            }

            if (!_pages.ContainsKey(page.GetType()))
            {
                _pages.Add(page.GetType(), pageKey);
            }

            return(page);
        }
示例#11
0
        private Page GetPage(PageKey pageKey, Dictionary <string, object> parameters = null)
        {
            Page page;

            ResolverOverride[] resolverOverrides = null;
            if (parameters != null && parameters.Count() > 0)
            {
                resolverOverrides = new ResolverOverride[parameters.Count()];
                for (int i = 0; i < parameters.Count(); i++)
                {
                    var dictionaryItem = parameters.ElementAt(i);
                    resolverOverrides[i] = new ParameterOverride(dictionaryItem.Key, dictionaryItem.Value);
                }
            }

            switch (pageKey)
            {
            case PageKey.Home:
                page = (ContentPage)ContainerManager.Container.Resolve(typeof(Home), typeof(Home).ToString());
                break;

            case PageKey.Login:
                page = (ContentPage)ContainerManager.Container.Resolve(typeof(Login), typeof(Login).ToString());
                break;

            case PageKey.Signup:
                page = (ContentPage)ContainerManager.Container.Resolve(typeof(Signup), typeof(Signup).ToString());
                break;

            case PageKey.Search:
                page = resolverOverrides != null ? (ContentPage)ContainerManager.Container.Resolve(typeof(Search), typeof(Search).ToString(), resolverOverrides) : (ContentPage)ContainerManager.Container.Resolve(typeof(Search), typeof(Search).ToString());
                break;

            case PageKey.RestaurantDetail:
                page = (ContentPage)ContainerManager.Container.Resolve(typeof(RestaurantDetail), typeof(RestaurantDetail).ToString());
                break;

            case PageKey.Filter:
                page = (ContentPage)ContainerManager.Container.Resolve(typeof(Filter), typeof(Filter).ToString());
                break;

            default:
                throw new ArgumentException(
                          $"No such page: {pageKey}. Did you forget to Register it?", nameof(pageKey));
            }

            if (!_pages.ContainsKey(page.GetType()))
            {
                _pages.Add(page.GetType(), pageKey);
            }

            return(page);
        }
        public virtual void ResolveWithOverrideTest(ResolverOverride instance)
        {
            var context = new TestContext() as IResolveContext;

            var resolver = instance.GetResolver <IResolveContext>(typeof(ResolverOverrideTests));

            Assert.IsNotNull(resolver);

            var value = resolver(ref context);

            Assert.AreSame(context, value);
        }
示例#13
0
        public void RegisterTypeAndResolveClassWithConstructor()
        {
            using (UnityContainer unityContainer = new UnityContainer())
            {
                unityContainer.RegisterType<IService, ServiceAdd>();

                ResolverOverride[] overrides = new ResolverOverride[]{new DependencyOverride(typeof(string), "title")};
                Manager manager = unityContainer.Resolve<Manager>(overrides);

                Assert.That(manager.Service.Calc(1, 2), Is.EqualTo(3));
                Assert.That(manager.Title, Is.EqualTo("title"));
            }
        }
示例#14
0
        public void RegisterTypeAndResolveClassWithConstructor()
        {
            using (UnityContainer unityContainer = new UnityContainer())
            {
                unityContainer.RegisterType <IService, ServiceAdd>();

                ResolverOverride[] overrides = new ResolverOverride[] { new DependencyOverride(typeof(string), "title") };
                Manager            manager   = unityContainer.Resolve <Manager>(overrides);

                Assert.That(manager.Service.Calc(1, 2), Is.EqualTo(3));
                Assert.That(manager.Title, Is.EqualTo("title"));
            }
        }
示例#15
0
        /// <summary>
        /// Build view model.
        /// </summary>
        /// <typeparam name="TViewModel">Type of the view model.</typeparam>
        /// <param name="resolverParameters">List of the parameters.</param>
        /// <returns>Returns view model instance.</returns>
        public TViewModel Build <TViewModel>(params ResolverParameter[] resolverParameters)
            where TViewModel : IRequestCloseViewModel
        {
            var @params = new ResolverOverride[resolverParameters.Length];

            for (var i = 0; i < resolverParameters.Length; i++)
            {
                var resolverParameter = resolverParameters[i];
                var parameter         = new ParameterOverride(resolverParameter.ParameterName, resolverParameter.ParameterValue);
                @params[i] = parameter;
            }

            return(this.container.Resolve <TViewModel>(@params));
        }
        public virtual void ResolveTest(ResolverOverride instance)
        {
            // Arrange
            var context = new TestContext() as IResolveContext;

            // Act
            var resolver = instance.GetResolver <IResolveContext>(typeof(ResolverOverrideTests));

            Assert.IsNotNull(resolver);

            // Validate
            var value = resolver(ref context);

            Assert.AreSame(OverrideValue, value);
        }
示例#17
0
        /// <summary>
        /// 定义仓储,带参
        /// </summary>
        /// <param name="dbType">数据库类型</param>
        /// <returns></returns>
        protected IDatabase BaseRepository(DatabaseType dbType)
        {
            IDatabase database = null;

            this.Logger(this.GetType(), "定义仓储,带参-BaseRepository", () =>
            {
                UnityIocHelper helper = UnityIocHelper.UnityIocInstance;
                //特别注意:此处的 connStringName 参数名称必须与IDatabase实现类的构造函数参数名称一致
                ResolverOverride parm = UnityIocHelper.GetParameterOverride(BaseParameterName, BaseConnStringName);

                DbHandlingCenter.DbType = dbType;

                database = helper.GetService <IDatabase>(parm);
            }, e =>
            {
            });
            return(database);
        }
示例#18
0
        public void Resolve_IChinookGenericRepository()
        {
            using (UnityContainer container = new UnityContainer())
            {
                // Arrange
                RegisterMappings(container);
                RegisterMappingsMongoDB(container);

                // Act
                ResolverOverride[] overrides = new ResolverOverride[]
                {
                    new ParameterOverride("unitOfWork", container.Resolve <IChinookUnitOfWork>())
                };
                var result = container.Resolve <IChinookGenericRepository <Album> >(overrides);

                // Assert
                Assert.IsType <ChinookGenericRepositoryMongoDB <Album> >(result);
            }
        }
示例#19
0
        public RoleRepositoryBase GetRepository(ConfigurationSettings settings)
        {
            return(base.Resolve <RoleRepositoryBase>(settings));

            Type           rf = typeof(RepositoryFactory);
            FieldInfo      uf = rf.GetField("unityContainer", BindingFlags.Static | BindingFlags.NonPublic);
            UnityContainer u  = (UnityContainer)uf.GetValue(null);

            ResolverOverride[] r = new ResolverOverride[0];

            switch (settings.ApiVersion)
            {
            case ApiVersion.V3:
            {
                CRMSecurityProvider.Repository.V3.CrmServiceCreatorV3 crmServiceCreatorV3 = new CRMSecurityProvider.Repository.V3.CrmServiceCreatorV3();

                //return new RoleRepositoryV3(crmServiceCreatorV3.CreateService(),new MarketingListToRoleConverterV3(),new CRMSecurityProvider.Repository.V3.ContactToUserConverterV3(),
                break;
            }

            case ApiVersion.V4:
            {
                CRMSecurityProvider.Repository.V4.CrmServiceCreatorV4 crmServiceCreatorV3 = new CRMSecurityProvider.Repository.V4.CrmServiceCreatorV4();

                //return new RoleRepositoryV3(crmServiceCreatorV4.CreateService(),new MarketingListToRoleConverterV4(),new CRMSecurityProvider.Repository.V4.ContactToUserConverterV4(),
                break;
            }

            case ApiVersion.V5:
            {
                CrmServiceCreatorV5 crmServiceCreatorV5 = new CrmServiceCreatorV5();

                return(new RoleRepositoryV5(u.Resolve <IOrganizationService>(r)
                                            , u.Resolve <CRMSecurityProvider.Repository.V5.IMarketingListToRoleConverterV5>(r)
                                            , u.Resolve <CRMSecurityProvider.Repository.V5.IContactToUserConverterV5>(r)
                                            , u.Resolve <CRMSecurityProvider.Repository.V5.UserRepositoryV5>(r)
                                            , u.Resolve <ICacheService>(r)));
            }
            }

            return(null); // base.GetRepository(settings);
        }
示例#20
0
        /// <summary>
        /// 定义仓储,带参
        /// </summary>
        /// <param name="connStringName">连接字符串配置项名称</param>
        /// <returns></returns>
        protected IDatabase BaseRepository(string connStringName)
        {
            IDatabase database = null;

            this.Logger(this.GetType(), "定义仓储,带参-BaseRepository", () =>
            {
                UnityIocHelper helper = UnityIocHelper.UnityIocInstance;
                //特别注意:此处的 connStringName 参数名称必须与IDatabase实现类的构造函数参数名称一致
                ResolverOverride parm = UnityIocHelper.GetParameterOverride(BaseParameterName, connStringName);

                string mapToName        = UnityIocHelper.GetmapToByName("DbContainer", "DatabaseType");
                DatabaseType dbType     = (DatabaseType)Enum.Parse(typeof(DatabaseType), mapToName, true);
                DbHandlingCenter.DbType = dbType;

                database = helper.GetService <IDatabase>(parm);
            }, e =>
            {
            });
            return(database);
        }
        public void GetHashCodeTest(ResolverOverride instance)
        {
            // Produces same result every time
            var typed = instance.GetHashCode();

            Assert.AreEqual(typed, instance.GetHashCode());

            var once = instance.OnType <ResolverOverrideTests>().GetHashCode();

            Assert.AreEqual(once, instance.GetHashCode());

            var twice = instance.OnType(typeof(object)).GetHashCode();

            Assert.AreEqual(twice, instance.GetHashCode());

            // But different value
            Assert.AreNotEqual(typed, once);
            Assert.AreNotEqual(typed, twice);
            Assert.AreNotEqual(twice, once);
        }
示例#22
0
        public T Resolve <T>(Dictionary <string, object> parameters = null) where T : class
        {
            if (parameters == null || parameters.Count == 0)
            {
                return((T)container.Resolve(typeof(T), string.Empty, null));
            }
            else
            {
                var parameterOverrides = new ResolverOverride[parameters.Count];

                int i = 0;
                foreach (var param in parameters)
                {
                    parameterOverrides[i] = new ParameterOverride(param.Key, param.Value);
                    i++;
                }

                return((T)container.Resolve(typeof(T), string.Empty, parameterOverrides));
            }
        }
示例#23
0
        private static ResolverOverride[] CreateOverrides(object[][] values)
        {
            if (values == null)
            {
                return(null);
            }

            var arguments = new ResolverOverride[values.Length];

            for (int i = 0; i < values.Length; i++)
            {
                if (values[i].Length != 2)
                {
                    throw new ArgumentException("Parameter is not specified correctly");
                }

                arguments[i] = new ParameterOverride(string.Empty + values[i][0], values[i][1]);
            }

            return(arguments);
        }
示例#24
0
        /// <summary>
        /// 连接数据库
        /// </summary>
        /// <param name="dbType">数据库类型</param>
        /// <param name="connConfigName">连接字符串配置项名称</param>
        /// <returns></returns>
        public IDatabase GetDatabase(DatabaseType dbType, string connConfigName)
        {
            string    cacheKey = string.Format("{0}:{1}", this.GetType().Name, string.Format("{0}_{1}_{2}", connConfigName, BaseParameterName, dbType.ToString()).GetMd5Code());
            IDatabase database = CallContext.GetData(cacheKey) as IDatabase;

            this.Logger(typeof(DbFactory), "连接数据库,带参-GetDatabase", () =>
            {
                if (database == null)
                {
                    UnityIocHelper helper = UnityIocHelper.UnityIocInstance;
                    //特别注意:此处的 connConfigName 参数名称必须与IDatabase实现类的构造函数参数名称一致
                    ResolverOverride parm = UnityIocHelper.GetParameterOverride(BaseParameterName, connConfigName);

                    DbTypeContainer.DbType = dbType;

                    database = helper.GetService <IDatabase>(parm);
                }
            }, e =>
            {
            });
            return(database);
        }
示例#25
0
 /// <summary>
 /// Function to retrieve Resolver Override for Authorization service.
 /// </summary>
 /// <returns>The Resolver Override</returns>
 public ResolverOverride[] ResolverOverrideForAuthorization()
 {
     authorizationServiceBaseAddress = DIContainer.Instance.Resolve<Workstation>().AuthorizationServiceBaseAddress;
     var resolverOverrideForGangway = new ResolverOverride[] { new ParameterOverride(BaseAddressParameterName, authorizationServiceBaseAddress) };
     return resolverOverrideForGangway;
 }
 public void EqualsWrongTest(ResolverOverride resolver)
 {
     // Validate
     Assert.IsFalse(resolver.Equals(this));
 }
示例#27
0
 /// <summary>
 /// 獲取指定接口的默認配置的實例
 /// </summary>
 /// <typeparam name="T">接口類型</typeparam>
 /// <param name="parameters">構造參數</param>
 /// <returns></returns>
 public virtual T Resolve <T>(ResolverOverride parameters)
 {
     return(Container.Resolve <T>(parameters));
 }
示例#28
0
 /// <summary>
 /// 根據register名稱及構造函數的參數加載接口實例
 /// unityBuilder.Resolve(register的name,new ParameterOverride(, entity));
 /// </summary>
 /// <typeparam name="T">接口類型</typeparam>
 /// <param name="name">register 名稱</param>
 /// <param name="parameters">構造參數</param>
 /// <returns></returns>
 public virtual T Resolve <T>(string name, ResolverOverride parameters)
 {
     return(Container.Resolve <T>(name, parameters));
 }
示例#29
0
 public void EqualsTest(ResolverOverride instance, object other, bool result)
 {
     // Validate
     Assert.AreEqual(result, instance.Equals(other));
 }