static void Main(string[] args)
        {
            Console.WriteLine("Sample.Background!");

            IConfiguration configuration = new ConfigurationBuilder()
                                           .SetBasePath(AppContext.BaseDirectory)
                                           .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                                           .AddEnvironmentVariables()
                                           .Build();

            IServiceCollection services = new ServiceCollection();

            services.AddSingleton <IUserHelper>(us =>
            {
                return(new UserHelperNull());
            });

            services.AddSingleton <IJobFactory>(pr =>
            {
                var jobFactory = new JobFactory(pr);
                return(jobFactory);
            });

            services.AddSingleton <SampleJob>();

            CoreIoC.Register(services, () => new DependencyInjectionConfig
            {
                Configuration = configuration,
                Template      = LoggingLayoutTemplate.WebApiLogTemplate
            });

            var serviceProvider = services.BuildServiceProvider();

            HostFactory.Run(configurator =>
            {
                configurator.SetServiceName("Sample.Background");
                configurator.SetDisplayName("Sample.Background");
                configurator.SetDescription("Sample background task processing service");

                configurator.RunAsLocalSystem();

                configurator.Service <SampleService>(serviceConfigurator =>
                {
                    var jobFactory = serviceProvider.GetRequiredService <IJobFactory>();

                    serviceConfigurator.ConstructUsing(() => new SampleService(jobFactory));

                    serviceConfigurator.WhenStarted((service, hostControl) =>
                    {
                        service.OnStart();
                        return(true);
                    });
                    serviceConfigurator.WhenStopped((service, hostControl) =>
                    {
                        service.OnStop();
                        return(true);
                    });
                });
            });
        }
Exemplo n.º 2
0
        /// <summary>
        /// This method gets called by the runtime. Use this method to add services to the container.
        /// </summary>
        /// <param name="services">Service Collection</param>
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers(options =>
            {
                options.Filters.Add(typeof(ErrorHandlingFilter));
                options.ModelBinderProviders.Insert(0, new ProviderModelBinder());
            }).ConfigureApiBehaviorOptions(options => { options.SuppressModelStateInvalidFilter = true; });

            services.AddCors();
            services.AddMemoryCache();

            // Register the Swagger generator, defining 1 or more Swagger documents
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Version     = "v1",
                    Title       = "Sample .NET Core DDD",
                    Description = "A .NET Core sample project based on DDD principles",
                    License     = new OpenApiLicense
                    {
                        Name = "MIT License",
                        Url  = new Uri("https://opensource.org/licenses/MIT")
                    }
                });

                // Set the comments path for the Swagger JSON and UI.
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                c.IncludeXmlComments(xmlPath);

                // Hiding the 'ViewModel' suffix in the Swagger UI
                c.CustomSchemaIds(type => type.Name.EndsWith("ViewModel") ? type.Name.Replace("ViewModel", string.Empty) : type.Name);

                // Defining authentication for requests in Swagger UI
                c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Description = "JWT Authorization header using the Bearer scheme.",
                    Type        = SecuritySchemeType.Http,
                    Scheme      = "Bearer"
                });

                c.AddSecurityRequirement(new OpenApiSecurityRequirement {
                    {
                        new OpenApiSecurityScheme {
                            Reference = new OpenApiReference {
                                Id   = "Bearer",
                                Type = ReferenceType.SecurityScheme
                            }
                        }, new List <string>()
                    }
                });
            });

            // Authentication
            var key = Encoding.ASCII.GetBytes(Settings.Secret);

            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata      = false;
                x.SaveToken                 = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(key),
                    ValidateIssuer           = false,
                    ValidateAudience         = false
                };
            });

            // Auto Mapper
            var mappingConfig = new MapperConfiguration(mc =>
            {
                mc.AddProfile(new MappingProfile());
            });

            IMapper mapper = mappingConfig.CreateMapper();

            services.AddSingleton(mapper);

            // Register User Helper
            services.AddHttpContextAccessor();
            services.AddScoped <IUserHelper, UserHelper>();

            // Register Domain
            CoreIoC.Register(services, () => new DependencyInjectionConfig
            {
                Configuration = Configuration,
                Template      = LoggingLayoutTemplate.WebApiLogTemplate
            });

            // Register SampleSettings
            services.Configure <SampleSettings>(Configuration.GetSection("Settings"));
        }