public static IKitbagBuilder AddEntityFramework <TDbContext>(this IKitbagBuilder builder, string sectionName = "Database", string?subsectionName = null) where TDbContext : DbContext
        {
            if (!builder.TryRegisterKitBag(sectionName))
            {
                return(builder);
            }

            var section = string.IsNullOrEmpty(subsectionName) ?
                          sectionName : $"{sectionName}:{subsectionName}";

            var properties = builder.GetSettings <PersistenceProperties>(section);

            if (properties.ConnectionString == null)
            {
                throw new ArgumentNullException("ConnectionString is empty");
            }

            builder.Services.AddSingleton(properties);
            builder.Services.AddDbContext <TDbContext>(optionsBuilder =>
            {
                optionsBuilder.UseSqlServer(properties.ConnectionString);
                optionsBuilder.ReplaceService <IValueConverterSelector, StronglyTypedIdValueConverterSelector>();
            });
            builder.Services.AddScoped <DbContext>(p => p.GetRequiredService <TDbContext>());
            return(builder);
        }
        public static IKitbagBuilder AddWebApi(this IKitbagBuilder builder, string sectionName = "WebApi")
        {
            if (!builder.TryRegisterKitBag(sectionName))
            {
                return(builder);
            }

            var assembly           = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault();
            var webApiOptions      = builder.GetSettings <WebApiOptions>(sectionName);
            var corsAllowedOrigins = webApiOptions.CorsAllowedOrigins?.ToArray() ?? new string[0];

            builder.Services
            .AddMvcCore(option => option.EnableEndpointRouting = false)
            .AddNewtonsoftJson(options =>
            {
                options.SerializerSettings.DateParseHandling = DateParseHandling.DateTimeOffset;
                options.SerializerSettings.Converters.Add(new StringEnumConverter());
            })
            .AddJsonOptions(options =>
            {
                options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
            })
            .AddApplicationPart(assembly)
            .AddControllersAsServices()
            .AddAuthorization()
            .AddApiExplorer()
            .AddCors(options => options.AddPolicy(
                         AllowedSpecificOrigins,
                         b => b.WithOrigins(corsAllowedOrigins)
                         .AllowAnyHeader()
                         .AllowAnyMethod()
                         ));

            return(builder);
        }
        public static IKitbagBuilder AddAppInsights(this IKitbagBuilder builder, string sectionName = "Logging")
        {
            if (!builder.TryRegisterKitBag(sectionName))
            {
                return(builder);
            }

            var loggingProperties = builder.GetSettings <LoggingProperties>(sectionName);

            builder.Services.AddSingleton(loggingProperties);
            if (!Enum.TryParse <LogLevel>(loggingProperties?.LogLevel?.Default, true, out var level))
            {
                level = LogLevel.Information;
            }

            builder.Services.AddLogging(loggerBuilder =>
            {
                string?key = loggingProperties?.ApplicationInsights?.InstrumentationKey;
                if (key == null)
                {
                    throw new ArgumentException("Instrumentation Key is missing");
                }
                loggerBuilder.AddApplicationInsights(key);
                loggerBuilder.AddFilter <ApplicationInsightsLoggerProvider>("", level);
            });
            builder.Services.AddApplicationInsightsTelemetry();

            return(builder);
        }
Esempio n. 4
0
        public static IKitbagBuilder AddSwagger(this IKitbagBuilder builder, string sectionName = "Swagger")
        {
            if (!builder.TryRegisterKitBag(sectionName))
            {
                return(builder);
            }

            var swaggerProperties = builder.GetSettings <SwaggerProperties>(sectionName);

            builder.Services.AddSingleton(swaggerProperties);

            builder.Services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc(swaggerProperties.ApiVersion, new OpenApiInfo
                {
                    Title       = swaggerProperties.ApiName,
                    Version     = swaggerProperties.ApiVersion,
                    Description = swaggerProperties.ApiDescription
                });

                var assemblies = AppDomain.CurrentDomain.GetAssemblies();
                var xmlPaths   = assemblies
                                 .Select(a => Path.Combine(AppContext.BaseDirectory, $"{a.GetName().Name}.xml"))
                                 .Where(a => File.Exists(a))
                                 .ToList();

                xmlPaths.ForEach(x => c.IncludeXmlComments(x));
            });
            return(builder);
        }
 public static IKitbagBuilder AddApiContext(this IKitbagBuilder builder, string sectionName = "WebApiContext")
 {
     if (!builder.TryRegisterKitBag(sectionName))
     {
         return(builder);
     }
     builder.Services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
     return(builder);
 }
Esempio n. 6
0
        public static IKitbagBuilder AddUnitOfWork(this IKitbagBuilder builder, string sectionName = "UnitOfWork")
        {
            if (!builder.TryRegisterKitBag(sectionName))
            {
                return(builder);
            }

            builder.Services.AddScoped <IUnitOfWork, Common.UnitOfWork>();
            builder.Services.AddScoped <ITransactionalUnitOfWork, Common.UnitOfWork>();
            return(builder);
        }
        public static IKitbagBuilder AddCQRSIntegrationEvents(this IKitbagBuilder builder, string sectionName = "CQRS.IntegrationEvents")
        {
            if (!builder.TryRegisterKitBag(sectionName))
            {
                return(builder);
            }

            builder.AddIntegrationEventHandlers();
            builder.AddInMemoryIntegrationEventDispatcher();
            return(builder);
        }
        public static IKitbagBuilder AddEntityFrameworkAuditTrail <TDbContext>(this IKitbagBuilder builder,
                                                                               string sectionName = "AuditTrail") where TDbContext : DbContext
        {
            if (!builder.TryRegisterKitBag(sectionName))
            {
                return(builder);
            }

            builder.Services.AddScoped <IAuditTrailRepository, AuditTrailRepository <TDbContext> >();
            builder.Services.AddScoped <IAuditTrailProvider, AuditTrailProvider <TDbContext> >();
            return(builder);
        }
        private static IKitbagBuilder AddDomainEventHandlers(this IKitbagBuilder builder, string sectionName = "DomainEvents")
        {
            if (!builder.TryRegisterKitBag(sectionName))
            {
                return(builder);
            }

            builder.Services.Scan(s =>
                                  s.FromAssemblies(AppDomain.CurrentDomain.GetAssemblies())
                                  .AddClasses(c => c.AssignableTo(typeof(IDomainEventHandler <>)))
                                  .AsImplementedInterfaces()
                                  .WithTransientLifetime());
            return(builder);
        }
Esempio n. 10
0
        public static IKitbagBuilder AddHttpClient(this IKitbagBuilder builder, string sectionName = "httpClient")
        {
            if (!builder.TryRegisterKitBag(sectionName))
            {
                return(builder);
            }

            var properties = builder.GetSettings <HttpClientProperties>(sectionName);

            builder.Services.AddSingleton(properties);
            builder.Services.AddHttpClient <IHttpClient, KitBagHttpClient>("kitbag.httpclient");
            builder.Services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            return(builder);
        }
Esempio n. 11
0
        public static IKitbagBuilder AddAzureQueue(this IKitbagBuilder builder, string sectionName = "MessageBus")
        {
            if (!builder.TryRegisterKitBag(sectionName))
            {
                return(builder);
            }
            var busProperties = builder.GetSettings <BusProperties>(sectionName);

            builder.Services.AddSingleton(busProperties);
            builder.Services.AddSingleton <IAzureQueueClient, AzureQueueClient>();
            builder.Services.AddSingleton <IEventBusSubscriber, QueueEventSubscriber>();
            builder.Services.AddSingleton <IBusPublisher, QueuePublisher>();

            return(builder);
        }
Esempio n. 12
0
        public static IKitbagBuilder AddDapperForQueries(this IKitbagBuilder builder, IDapperInitializer?dapperInitializer = null, string sectionName = "Dapper")
        {
            if (!builder.TryRegisterKitBag(sectionName))
            {
                return(builder);
            }

            dapperInitializer?.Init();
            builder.Services.AddSingleton <ISqlConnectionFactory, SqlConnectionFactory>();
            builder.Services.Decorate(typeof(IQueryHandler <,>), typeof(FilteredQueryHandler <,>));
            builder.Services.Decorate(typeof(IQueryHandler <,>), typeof(PagedQueryHandler <,>));
            builder.Services.Decorate(typeof(IQueryHandler <,>), typeof(SortedQueryHandler <,>));
            builder.Services.AddTransient <IDynamicParametersExtractor, DynamicParametersExtractor>();

            return(builder);
        }
Esempio n. 13
0
        private static IKitbagBuilder AddCommandHandlers(this IKitbagBuilder builder, string sectionName = "Commands")
        {
            if (!builder.TryRegisterKitBag(sectionName))
            {
                return(builder);
            }

            builder.Services.Scan(s =>
                                  s.FromAssemblies(AppDomain.CurrentDomain.GetAssemblies())
                                  .AddClasses(c =>
            {
                c.AssignableTo(typeof(ICommandHandler <>));
                c.Where((t) => !t.IsGenericType);
            })
                                  .AsImplementedInterfaces()
                                  .WithTransientLifetime());
            return(builder);
        }
Esempio n. 14
0
        public static IKitbagBuilder AddCQRS(this IKitbagBuilder builder, string sectionName = "CQRS")
        {
            if (!builder.TryRegisterKitBag(sectionName))
            {
                return(builder);
            }

            builder.AddCommandHandlers();
            builder.AddInMemoryCommandDispatcher();

            builder.AddDomainEventHandlers();
            builder.AddInMemoryDomainEventDispatcher();

            builder.AddQueryHandlers();
            builder.AddInMemoryQueryDispatcher();

            return(builder);
        }
Esempio n. 15
0
        public static IKitbagBuilder AddAzureAD(
            this IKitbagBuilder builder,
            string sectionName    = "AzureAD",
            string?subsectionName = null)
        {
            if (!builder.TryRegisterKitBag(sectionName))
            {
                return(builder);
            }
            var section = string.IsNullOrEmpty(subsectionName) ? sectionName : $"{sectionName}:{subsectionName}";

            builder.Services.AddProtectedWebApi(options =>
            {
                builder.GetSettings(section, options);
                options.Events = new JwtBearerEvents();
                options.Events.OnAuthenticationFailed = (c) =>
                {
                    if (c.Exception is UnauthorizedAccessException)
                    {
                        c.Fail(c.Exception);
                    }
                    return(Task.CompletedTask);
                };
                options.Events.OnChallenge = (c) =>
                {
                    if (string.IsNullOrEmpty(c.ErrorDescription))
                    {
                        c.ErrorDescription = c.AuthenticateFailure?.Message;
                    }
                    return(Task.CompletedTask);
                };
            }, options =>
            {
                builder.GetSettings(section, options);
            });

            return(builder);
        }