Exemple #1
0
        public void TestBindWhenIntoByType()
        {
            var container = new InjectionContainer();

            container.Bind <IMockInterface>().To <MockIClassWithAttributes>().WhenInto(typeof(MockClassVerySimple));
            container.Bind <IMockInterface>().To <MockIClassWithoutAttributes>().WhenInto(typeof(MockClassSimple));

            var instance1 = container.Resolve <MockClassVerySimple>();
            var instance2 = container.Resolve <MockClassSimple>();

            Assert.AreEqual(typeof(MockIClassWithAttributes), instance1.field.GetType());
            Assert.AreEqual(typeof(MockIClassWithoutAttributes), instance2.field.GetType());
        }
Exemple #2
0
        public void TestBindWhenComplexConditionByMemberName()
        {
            var container = new InjectionContainer(ResolutionMode.RETURN_NULL);

            container.Bind <IMockInterface>().To <MockIClass>().When(context =>
                                                                     context.memberName.Equals("property2")
                                                                     );
            container.Bind <IMockInterface>().To <MockIClass>().When(context =>
                                                                     context.memberName.Equals("field2")
                                                                     );
            container.Bind <MockClassToDepend>().ToSelf().When(context =>
                                                               context.member.Equals(InjectionMember.Method) &&
                                                               context.memberName.Equals("field2")
                                                               );
            container.Bind <MockClassInjectAll>().ToSingleton();

            var instance = container.Resolve <MockClassInjectAll>();

            Assert.IsNull(instance.property1);
            Assert.AreEqual(typeof(MockIClass), instance.property2.GetType());
            Assert.IsNull(instance.property3);

            Assert.IsNull(instance.field1);
            Assert.AreEqual(typeof(MockIClass), instance.field2.GetType());
            Assert.IsNull(instance.field3);

            Assert.AreNotEqual(instance.property2, instance.field2);

            Assert.IsNull(instance.fieldFromConstructor1);
            Assert.IsNull(instance.fieldFromConstructor2);

            Assert.IsNull(instance.fieldFromMethod1);
            Assert.IsNotNull(instance.fieldFromMethod2);
        }
        public async Task <ActionResult> Information()
        {
            //类型列表
            int parentid = TypeInfoParentIds.Information;
            var list     = await InjectionContainer.Resolve <ITypeInfoStorage>().GetListAsync(parentid);

            ViewBag.TypeList = list.Where(i => i.parentid == parentid).OrderBy(i => i.sort).Select(i => new
            {
                i.typeid,
                i.text
            });
            // 分页列表
            var pageList = await InjectionContainer.Resolve <IArticleStorage>().GetPagedListAsync(1, 10, "", list.Count() > 0 ? list.First().typeid : 0, -1, -1, -1, "created_DESC");

            ViewBag.InformationList = new
            {
                list  = pageList.RowSet.Select(i => Projections.GetArticleProjection(i)),
                count = pageList.Count
            };
            //热点阅读
            var hotList = await InjectionContainer.Resolve <IArticleStorage>().GetPagedListAsync(1, 6, "", 0, 1, -1, -1, "created_DESC");

            ViewBag.HotList = pageList.RowSet.Select(i => Projections.GetArticleProjection(i));

            return(View());
        }
Exemple #4
0
        public void TestResolutionModeReturnNullNotBound()
        {
            var container = new InjectionContainer(ResolutionMode.RETURN_NULL);

            var instance = container.Resolve <MockClassManyInterfaces>();

            Assert.IsNull(instance);
        }
Exemple #5
0
        public void TestBindAsIdentifierWhenIntoByType()
        {
            var container = new InjectionContainer();

            container.Bind<IMockInterface>()
                .To<MockIClassWithAttributes>().WhenInto(typeof(MockClassVerySimple));
            container.Bind<IMockInterface>()
                .To<MockIClassWithoutAttributes>().WhenInto(typeof(MockClassSimple)).As("singleton");
            container.Bind<IMockInterface>()
                .To<MockIClass>().WhenInto(typeof(MockClassSimple)).As("test");

            var instance1 = container.Resolve<MockClassVerySimple>();
            var instance2 = container.Resolve<MockClassSimple>();

            Assert.AreEqual(typeof(MockIClassWithAttributes), instance1.field.GetType());
            Assert.IsNull(instance2.field);
            Assert.AreEqual(typeof(MockIClassWithoutAttributes), instance2.property.GetType());
        }
Exemple #6
0
        public void TestBindAsIdentifierWhenIntoByType()
        {
            var container = new InjectionContainer();

            container.Bind <IMockInterface>()
            .To <MockIClassWithAttributes>().WhenInto(typeof(MockClassVerySimple));
            container.Bind <IMockInterface>()
            .To <MockIClassWithoutAttributes>().WhenInto(typeof(MockClassSimple)).As("singleton");
            container.Bind <IMockInterface>()
            .To <MockIClass>().WhenInto(typeof(MockClassSimple)).As("test");

            var instance1 = container.Resolve <MockClassVerySimple>();
            var instance2 = container.Resolve <MockClassSimple>();

            Assert.AreEqual(typeof(MockIClassWithAttributes), instance1.field.GetType());
            Assert.IsNull(instance2.field);
            Assert.AreEqual(typeof(MockIClassWithoutAttributes), instance2.property.GetType());
        }
Exemple #7
0
        public void TestResolutionModeReturnNullBound()
        {
            var container = new InjectionContainer(ResolutionMode.ALWAYS_RESOLVE);

            container.Bind <IMockInterface1>().ToSingleton <MockClassManyInterfaces>();

            var instance = container.Resolve <IMockInterface1>();

            Assert.NotNull(instance);
        }
Exemple #8
0
        public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
        {
            //判断是否匿名访问的接口或控制器
            if (!context.ActionContext.ActionDescriptor.GetCustomAttributes <AllowAnonymousAttribute>(false).Any() &&
                !context.ActionContext.ControllerContext.ControllerDescriptor.GetCustomAttributes <AllowAnonymousAttribute>(false).Any())
            {
                string token = "";
                //从url中获取token
                var qs = context.Request.GetQueryNameValuePairs().ToDictionary(i => i.Key, i => i.Value);
                if (qs.ContainsKey("token"))
                {
                    token = qs["token"];
                }
                else
                {
                    var httpContext = context.Request.GetHttpContext();
                    token = httpContext.Request["token"];
                }
                if (string.IsNullOrWhiteSpace(token) || Regex.Matches(token, @"\.").Count != 4)
                {
                    throw new HttpResponseException(HttpStatusCode.Unauthorized);
                }

                //解析token荷载部分
                JwePayload payload = null;
                try
                {
                    payload = JweProvider.Decode(token, JwtCommon.SignKey);
                }
                catch (Exception e)
                {
                    LogProvider.Error.Error(e, "解析jwepayload失败");
                }
                if (payload == null)
                {
                    throw new HttpResponseException(HttpStatusCode.Unauthorized);
                }
                //判断是否过期
                if (payload.IsExpires())
                {
                    throw new HttpResponseException(HttpStatusCode.Unauthorized);
                }
                var user = await InjectionContainer.Resolve <IUserStorage>().GetAsync(payload.uid);

                if (user == null)
                {
                    throw new HttpResponseException(HttpStatusCode.Unauthorized);
                }
                //保存user
                context.Request.Properties.Add(HttpPropertyKeys.AuthorizedUser, user);
                //保存jwe payload
                context.Request.Properties.Add(HttpPropertyKeys.JwePayload, payload);
            }
        }
Exemple #9
0
        public void TestResolveFromFactoryInstance()
        {
            var container = new InjectionContainer();

            container.Bind <MockIClassWithAttributes>().ToFactory(new MockFactory());
            var instance = container.Resolve <MockIClassWithAttributes>();

            Assert.NotNull(instance);
            Assert.AreEqual("Created from a Factory", instance.field1);
            Assert.AreEqual("Created from a Factory", instance.field2);
            Assert.AreEqual("Created from a Factory", instance.field3);
        }
        public void Resolve_SomeClass_Correct()
        {
            //Arrange
            var container = new InjectionContainer();
            //Act
            var instance = container.Resolve <someClass_c>();

            //Assert
            Assert.AreEqual(
                true,
                instance != null &&
                instance.b != null);
        }
        /// <summary>
        /// 使用指定验证类验证对应的实体
        /// 若验证不同过,则抛出第一个错误异常
        /// </summary>
        /// <typeparam name="V">验证类</typeparam>
        /// <typeparam name="E">实体类</typeparam>
        /// <param name="entity"></param>
        public static void ThrowIfInValidate <V, E>(E entity)
            where V : AbstractValidator <E>
        {
            var validator = InjectionContainer.Resolve <V>();
            var result    = validator.Validate(entity);

            if (!result.IsValid)
            {
                //抛出第一个验证错误信息 //error.PropertyName
                var error = result.Errors[0];
                throw new ArgumentException(error.ErrorMessage);
            }
        }
Exemple #12
0
        public void TestResolutionModeReturnNullSingleton()
        {
            var container = new InjectionContainer(ResolutionMode.RETURN_NULL);

            container.Bind <IMockInterface>().ToSingleton <MockIClassWithAttributes>();

            var instance = container.Resolve <IMockInterface>();

            Assert.IsNotNull(instance);
            Assert.AreEqual(typeof(MockIClassWithAttributes), instance.GetType());
            Assert.Null(((MockIClassWithAttributes)instance).field4);
            Assert.Null(((MockIClassWithAttributes)instance).property4);
        }
Exemple #13
0
        public void TestResolveMultiple()
        {
            var container = new InjectionContainer();

            container.Bind <IMockInterface>().To <MockIClass>();
            container.Bind <IMockInterface>().To <MockIClassWithAttributes>();
            container.Bind <IMockInterface>().To <MockIClassWithoutAttributes>();

            var instance = container.Resolve <MockClassMultiple>();

            Assert.AreEqual(3, instance.list.Length);
            Assert.AreEqual(typeof(MockIClass), instance.list[0].GetType());
            Assert.AreEqual(typeof(MockIClassWithAttributes), instance.list[1].GetType());
            Assert.AreEqual(typeof(MockIClassWithoutAttributes), instance.list[2].GetType());
        }
        public async Task <ActionResult> Index()
        {
            string key = "homecontroller->banner.index.list";

            if (!CacheProvider.TryGet(key, out IEnumerable <Banner> list))
            {
                list = await InjectionContainer.Resolve <IBannerStorage>().GetListAsync(10, (int)BannerType.首页, "sort_DESC");

                if (list.Any())
                {
                    CacheProvider.Set(key, list, TimeSpan.FromMinutes(10));
                }
            }
            ViewBag.BannerList = list;

            return(View(list));
        }
        public async Task <ActionResult> InformationDetail(int id)
        {
            var storage = InjectionContainer.Resolve <IArticleStorage>();
            var model   = await storage.GetAsync(id);

            if (model == null)
            {
                throw new Exception("指定资讯详情不存在");
            }
            //更新查看数
            model.seecount++;
            await storage.UpdateAsync(model);

            //获取页面数据
            var data = await storage.GetViewDataAsync(id);

            data.Current = model;

            return(View(data));
        }
        public async Task <ActionResult> Case()
        {
            //类型列表
            int parentid = 2;
            var list     = await InjectionContainer.Resolve <ITypeInfoStorage>().GetListAsync(parentid);

            ViewBag.TypeList = list.Where(i => i.parentid == parentid).Select(i => new
            {
                i.typeid,
                i.text
            });
            // 分页列表
            var pageList = await InjectionContainer.Resolve <ICaseInfoStorage>().GetPagedListAsync(1, 6, "", list.Count() > 0 ? list.First().typeid : 0, "");

            ViewBag.CaseList = new
            {
                list  = pageList.RowSet.Select(i => Projections.GetCaseProjection(i)),
                count = pageList.Count
            };

            return(View());
        }
Exemple #17
0
        public void TestResolveMultiple()
        {
            var container = new InjectionContainer();

            container.Bind<IMockInterface>().To<MockIClass>();
            container.Bind<IMockInterface>().To<MockIClassWithAttributes>();
            container.Bind<IMockInterface>().To<MockIClassWithoutAttributes>();

            var instance = container.Resolve<MockClassMultiple>();

            Assert.AreEqual(3, instance.list.Length);
            Assert.AreEqual(typeof(MockIClass), instance.list[0].GetType());
            Assert.AreEqual(typeof(MockIClassWithAttributes), instance.list[1].GetType());
            Assert.AreEqual(typeof(MockIClassWithoutAttributes), instance.list[2].GetType());
        }
Exemple #18
0
        public void TestResolveFromFactoryType()
        {
            var container = new InjectionContainer();

            container.Bind<MockIClassWithAttributes>().ToFactory(typeof(MockFactory));
            var instance = container.Resolve<MockIClassWithAttributes>();

            Assert.NotNull(instance);
            Assert.AreEqual("Created from a Factory", instance.field1);
            Assert.AreEqual("Created from a Factory", instance.field2);
            Assert.AreEqual("Created from a Factory", instance.field3);
        }
Exemple #19
0
        public void TestBindWhenIntoByType()
        {
            var container = new InjectionContainer();

            container.Bind<IMockInterface>().To<MockIClassWithAttributes>().WhenInto(typeof(MockClassVerySimple));
            container.Bind<IMockInterface>().To<MockIClassWithoutAttributes>().WhenInto(typeof(MockClassSimple));

            var instance1 = container.Resolve<MockClassVerySimple>();
            var instance2 = container.Resolve<MockClassSimple>();

            Assert.AreEqual(typeof(MockIClassWithAttributes), instance1.field.GetType());
            Assert.AreEqual(typeof(MockIClassWithoutAttributes), instance2.field.GetType());
        }