コード例 #1
0
        public static void AddFreeSql(this IServiceCollection service)
        {
            var freeSql = service.BuildServiceProvider().GetRequiredService <IOptions <FreeSqlConfig> >().Value;

            //注入FreeSql
            service.AddSingleton <IFreeSql>(f =>
            {
                var log         = f.GetRequiredService <ILogger <IFreeSql> >();
                var freeBuilder = new FreeSqlBuilder()
                                  .UseAutoSyncStructure(true)
                                  .UseConnectionString(freeSql.DataType, freeSql.MasterConnetion)
                                  .UseLazyLoading(true)
                                  .UseMonitorCommand(
                    executing =>
                {
                    //执行中打印日志
                    log.LogInformation(executing.CommandText);
                }
                    //   null,
                    //(executed, t) =>
                    //{
                    //    //执行后打印日志
                    //    log.LogWarning(t);
                    //}
                    )
                                  .UseCache(null);
                if (freeSql.SlaveConnections?.Count > 0)//判断是否存在从库
                {
                    freeBuilder.UseSlave(freeSql.SlaveConnections.Select(x => x.ConnectionString).ToArray());
                }
                var freesql = freeBuilder.Build();
                //我这里禁用了导航属性联级插入的功能
                freesql.SetDbContextOptions(opt => opt.EnableAddOrUpdateNavigateList = false);
                return(freesql);
            });
            //注入Uow
            service.AddScoped <IRepositoryUnitOfWork>(f =>
                                                      f.GetRequiredService <IFreeSql>().CreateUnitOfWork());
            //注入HttpContextAccessor 可以从IOC中拿到HttpContext的内容
            service.AddHttpContextAccessor();
            service.TryAddSingleton <IActionContextAccessor, ActionContextAccessor>();
            //注入当前用户 利用了缓存查询当前用户信息
            service.AddScoped <CurrentUser>(f => f.GetRequiredService <IHttpContextAccessor>().HttpContext?.User?.GetCurrentUser(f));
            //使用类库Scrutor做发现注入类库和服务
            service.AddServer(typeof(IRepKey));
            service.AddServer(typeof(IDomainBase));
            //Automapper和配置模板 注入
            service.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
        }
コード例 #2
0
        /// <summary>
        /// 直接从配置文件读取配置
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="service"></param>
        public static void CreateFreeSql <T>(this IServiceCollection service)
        {
            service.AddSingleton(f =>
            {
                var current = f.GetService <FreeSqlCollectionConfig>().FreeSqlConfigs?.FirstOrDefault(x => x.Key == typeof(T).Name) ?? throw new ArgumentNullException(nameof(FreeSqlCollectionConfig),
                                                                                                                                                                       $"appSettings.json文件未检测到{typeof(T).Name}对象");
                var builder = new FreeSqlBuilder()
                              .UseConnectionString(current.DataType, current.MasterConnection)
                              .UseAutoSyncStructure(current.IsSyncStructure);

                if (current.SlaveConnections.Count > 0)
                {
                    builder.UseSlave(current.SlaveConnections.ToArray());
                }
                var res             = builder.Build <T>();
                res.Aop.CurdAfter  += (s, e) => Aop_CurdAfter(s, e, f.GetService <ILogger <IFreeSql <T> > >());
                res.Aop.AuditValue += (s, e) => Aop_Auditer(s, e, f);
                res.GlobalFilter.Apply <IDeleted>(SysConsts.DELETED_FILTER, x => !x.IsDeleted);
                res.GlobalFilter.Apply <IEnabled>(SysConsts.ENABLED_FILTER, x => x.Enabled == true);
                return(res);
            });

            service.AddScoped <IUnitOfWork <T>, UnitOfWork <T> >();
        }
コード例 #3
0
        public static void AddSimpleFreeSql(this IServiceCollection service)
        {
            var thisFontColor = (int)Console.ForegroundColor;
            var newFontColor  = (ConsoleColor)((thisFontColor + 1) > 15 ? 0 : (thisFontColor + 1));


            if (service == null)
            {
                throw new ArgumentNullException(nameof(service));
            }

            var freeSql = service.BuildServiceProvider().GetRequiredService <IOptions <FreeSqlCollectionConfig> >().Value;
            var config  = freeSql.FreeSqlCollections.Where(it => it.Key == "IHRSystem").FirstOrDefault();

            if (config == null)
            {
                throw new ArgumentNullException(nameof(config));
            }

            //注入FreeSql
            service.AddScoped(f =>
            {
                var log         = f.GetRequiredService <ILogger <IFreeSql> >();
                var freeBuilder = new FreeSqlBuilder()
                                  .UseAutoSyncStructure(false)
                                  .UseConnectionString(config.DataType, config.MasterConnetion)
                                  .UseLazyLoading(true)
                                  .UseMonitorCommand(aop =>
                {
                    //Console.ForegroundColor = newFontColor;
                    //Console.WriteLine("=================================================================================\n");
                    //Console.WriteLine(aop.CommandText + "\n");

                    string parametersValue = "";
                    for (int i = 0; i < aop.Parameters.Count; i++)
                    {
                        parametersValue += $"{aop.Parameters[i].ParameterName}:{aop.Parameters[i].Value}" + ";\n";
                    }
                    if (!string.IsNullOrWhiteSpace(parametersValue))
                    {
                        //Console.WriteLine(parametersValue);

                        log.LogInformation
                        (
                            "\n=================================================================================\n\n"
                            + aop.CommandText + "\n\n"
                            + parametersValue +
                            "\n=================================================================================\n\n"
                        );
                    }

                    log.LogInformation
                    (
                        "\n=================================================================================\n\n"
                        + aop.CommandText +
                        "\n\n=================================================================================\n"
                    );

                    //Console.WriteLine("=================================================================================\n");
                    //Console.ForegroundColor = (ConsoleColor)thisFontColor;
                });
                if (config.SlaveConnections?.Count > 0)//判断是否存在从库
                {
                    freeBuilder.UseSlave(config.SlaveConnections.Select(x => x.ConnectionString).ToArray());
                }
                var freesql = freeBuilder.Build();
                //我这里禁用了导航属性联级插入的功能
                freesql.SetDbContextOptions(opt => opt.EnableAddOrUpdateNavigateList = false);
                return(freesql);
            });

            //注入Uow
            service.AddScoped(f => f.GetRequiredService <IFreeSql>().CreateUnitOfWork());
        }
コード例 #4
0
        /// <summary>
        /// 直接从配置文件读取配置
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="service"></param>
        public static void AddFreeSql <T>(this IServiceCollection service)
        {
            //var thisFontColor = (int)Console.ForegroundColor;
            //var newFontColor = (ConsoleColor)((thisFontColor + 1) > 15 ? 0 : (thisFontColor + 1));

            service.AddSingleton(f =>
            {
                var log     = f.GetRequiredService <ILogger <IFreeSql> >();
                var current = f.GetRequiredService <IOptions <FreeSqlCollectionConfig> >().Value.FreeSqlCollections.FirstOrDefault(x => x.Key == typeof(T).Name);
                var builder = new FreeSqlBuilder()
                              .UseConnectionString(current.DataType, current.MasterConnetion)
                              .UseAutoSyncStructure(current.IsSyncStructure)
                              .UseMonitorCommand(executing =>
                {
                    executing.CommandTimeout = current.CommandTimeout;

                    if (current.DebugShowSql)
                    {
                        //Console.ForegroundColor = newFontColor;
                        //Console.WriteLine("\n=================================================================================\n");
                        //Console.WriteLine(executed.CommandText + "\n");

                        string parametersValue = "";
                        if (current.DebugShowSqlPparameters)
                        {
                            for (int i = 0; i < executing.Parameters.Count; i++)
                            {
                                parametersValue += $"{executing.Parameters[i].ParameterName}:{executing.Parameters[i].Value}" + ";\n";
                            }
                        }
                        if (!string.IsNullOrWhiteSpace(parametersValue))
                        {
                            //Console.WriteLine(parametersValue);
                            log.LogDebug
                            (
                                "\n=================================================================================\n\n"
                                + executing.CommandText + "\n\n"
                                + "\n" + parametersValue +
                                "\n=================================================================================\n\n"
                            );
                        }
                        else
                        {
                            log.LogDebug
                            (
                                "\n=================================================================================\n\n"
                                + executing.CommandText +
                                "\n\n=================================================================================\n"
                            );
                        }
                        //Console.WriteLine("=================================================================================\n");
                        //Console.ResetColor();
                    }
                });
                if (current.SlaveConnections.Count > 0)//判断是否存在从库
                {
                    builder.UseSlave(current.SlaveConnections.Select(x => x.ConnectionString).ToArray());
                }
                var res = builder.Build <T>();

                #region //使用FreeSql AOP做对应的业务拓展,有需要自行实现

                //res.GlobalFilter.Apply<IDeleted>(SysConsts.IsDeletedDataFilter, x => !x.IsDeleted);
                //res.GlobalFilter.Apply<IEnabled>(SysConsts.IsEnabledDataFilter, x => x.Enabled == true);
                //res.Aop.ConfigEntity += new EventHandler<ConfigEntityEventArgs>((_, e) =>
                //{
                //    var attrs = e.EntityType.GetCustomAttributes(typeof(IndexAttribute), false);
                //    foreach (var attr in attrs)
                //    {
                //        var temp = attr as IndexAttribute;
                //        e.ModifyIndexResult.Add(new FreeSql.DataAnnotations.IndexAttribute(temp.Name, temp.Fields, temp.IsUnique));
                //    }
                //});

                #endregion //使用FreeSql AOP做对应的业务拓展,有需要自行实现

                return(res);
            });
            service.AddScoped <IUnitOfWork <T>, UnitOfWork <T> >();
        }