Beispiel #1
0
        public static void Register()
        {
            var builder = new ContainerBuilder();

            builder.RegisterControllers(Assembly.GetExecutingAssembly());
            builder.RegisterFilterProvider();

            foreach (var con in ConfigUtil.GetConnStrings())
            {
                builder.Register(c => new SqlConnection(con.Value))
                .Named <IDbConnection>(con.Key)
                .InstancePerRequest();
            }

            builder.RegisterType <UnitOfWork>().As <IUnitOfWork>().InstancePerRequest();
            builder.Register <Func <string, IDbConnection> >(c =>
            {
                var ic = c.Resolve <IComponentContext>();
                return(named => ic.ResolveNamed <IDbConnection>(named));
            });
            builder.RegisterGeneric(typeof(Repository <>)).As(typeof(IRepository <>)).InstancePerRequest();

            RedisProxy.Initialize();
            var redis    = new RedisProxy();
            var memcache = new MemcacheProxy();

            builder.Register(c => redis).As <ICache>().SingleInstance();
            builder.Register(c => redis).As <IRedisProxy>().SingleInstance();
            builder.Register(c => memcache).As <IMemcacheProxy>().SingleInstance();

            builder.RegisterType <MongoProxy>().As <IMongoProxy>().SingleInstance();
            builder.RegisterType <Logger>().As <ILog>().SingleInstance();
            builder.RegisterType <ServiceBus>().As <IServiceBus>().SingleInstance();
            builder.RegisterType <ExcelClient>().As <IExcelClient>().InstancePerRequest();

            var assemblies = BuildManager.GetReferencedAssemblies()
                             .Cast <Assembly>()
                             .Where(a => a.GetTypes().FirstOrDefault(t => t.GetInterfaces().Contains(typeof(IService))) != null)
                             .ToArray();

            builder.RegisterAssemblyTypes(assemblies)//查找程序集中以Svc结尾的类型
            .Where(t => t.GetInterfaces().Contains(typeof(IService)) && t.Name.EndsWith("Svc"))
            .AsImplementedInterfaces().InstancePerRequest();

            builder.RegisterAssemblyTypes(assemblies)
            .Where(t => t.GetInterfaces().Contains(typeof(IService)))
            .AsSelf()
            .InstancePerLifetimeScope();

            #region API Processor Register

            builder.RegisterType <ProcessorFactory>().As <IProcessorFactory>().InstancePerRequest();

            foreach (var type in ProcessorUtil.GetProcessors())
            {
                builder.RegisterType(type)
                .Named <IProcessor>(ProcessorUtil.GetBizCode(type))
                .InstancePerRequest();
            }

            builder.Register <Func <string, IProcessor> >(c =>
            {
                var ic = c.Resolve <IComponentContext>();
                return(name => ic.ResolveNamed <IProcessor>(name));
            });

            #endregion

            var container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
Beispiel #2
0
        public BaseResponse Index([FromUri] RequestData model)
        {
            var watcher = new Stopwatch();

            watcher.Start();

            var          response   = new BaseResponse();
            BaseResponse exResponse = null;

            var         requestId             = string.Empty;
            var         requestDataJson       = string.Empty;
            var         userDataJson          = string.Empty;
            var         logMsg                = new ApiLogMessage();
            var         bizCode               = string.Empty;
            var         urlEncodedUserData    = string.Empty;
            var         urlEncodedRequestData = string.Empty;
            var         parmUserData          = string.Empty;
            var         parmRequestData       = string.Empty;
            BaseRequest baseRequest           = null;
            Merchant    merchant              = null;

            try
            {
                if (model.IsNull() || model.Cmd.IsNullOrWhiteSpace())
                {
                    return(BaseResponse.Create(ApiEnum.ResponseCode.处理失败, "无效请求", null, 0));
                }
                bizCode = ProcessorUtil.GetBizCode(model.Cmd);
                if (bizCode.IsNullOrWhiteSpace())
                {
                    return(BaseResponse.Create(ApiEnum.ResponseCode.无效交易类型, "无效交易类型", null, 0));
                }
                baseRequest = ProcessorUtil.GetRequest(bizCode, model.ToJson());
                if (baseRequest == null)
                {
                    return(BaseResponse.Create(ApiEnum.ResponseCode.处理失败, "无效请求", null, 0));
                }
                //验证参数
                var errMsg = "";
                if (!ModelVerify(baseRequest, out errMsg))
                {
                    response = BaseResponse.Create(ApiEnum.ResponseCode.参数不正确, errMsg, null, 0);
                    return(response);
                }

                //商户校验
                if (!MerchantVerify(baseRequest, out merchant, out errMsg))
                {
                    response = BaseResponse.Create(ApiEnum.ResponseCode.处理失败, errMsg, null, 0);
                    return(response);
                }

                //验证签名
                if (!VerifySign(baseRequest, merchant))
                {
                    response = BaseResponse.Create(ApiEnum.ResponseCode.无效调用凭证, "签名不正确", null, 0);
                    return(response);
                }
                var processor = this.factory.Create(bizCode);
                response = processor.Process(baseRequest);
            }
            catch (Exception ex)
            {
                log.Error(ex);
                response       = BaseResponse.Create(ApiEnum.ResponseCode.系统内部错误, "不好意思,程序开小差,正在重启" + ex.ToString(), 0);
                exResponse     = BaseResponse.Create(ApiEnum.ResponseCode.系统内部错误, ex.ToString(), 0);
                logMsg.IsError = true;
            }
            finally
            {
                //WriteRequestInfo(userData, requestData, requestId, bizCode);

                watcher.Stop();
                var duration = watcher.Elapsed.TotalMilliseconds;

                var logStr = string.Empty;
                logStr += string.Format("【请求报文】RequestId:{0}", requestId) + Environment.NewLine;
                logStr += string.Format("UserData:{0}", urlEncodedUserData) + Environment.NewLine;
                logStr += string.Format("RequestData:{0}", urlEncodedRequestData) + Environment.NewLine;
                logStr += string.Format("【响应报文】{0}", response.ToJson());
                logStr += string.Format("【耗时】{0}毫秒", duration);
                log.Info(logStr.ToString());


                logMsg.UserDataStr    = urlEncodedUserData;
                logMsg.RequestDataStr = urlEncodedRequestData;
                logMsg.RequestId      = requestId;
                logMsg.LogTime        = DateTime.Now;


                logMsg.RequestJson = requestDataJson;
                logMsg.Response    = exResponse.IsNull() ? response.ToJson() : exResponse.ToJson();
                logMsg.Duration    = duration;

                if (AppConfig.LogType == LogType.MQ)
                {
                    try
                    {
                        this.bus.Publish(logMsg);
                    }
                    catch (Exception ex)
                    {
                        log.Error("写入MQ失败,RequestId:{0}\r\n{1}".Fmt("", ex.ToString()));
                    }
                }
            }

            return(response);
        }