Пример #1
0
        public void MultiRegistrationServiceTypes_AreRegistered_MultipleTimes()
        {
            // Arrange
            var services = new ServiceCollection();

            // Register a mock implementation of each service, AddMvcServices should add another implemenetation.
            foreach (var serviceType in MutliRegistrationServiceTypes)
            {
                var mockType = typeof(Mock <>).MakeGenericType(serviceType.Key);
                services.Add(ServiceDescriptor.Transient(serviceType.Key, mockType));
            }

            // Act
            MvcServiceCollectionExtensions.AddMvcServices(services);

            // Assert
            foreach (var serviceType in MutliRegistrationServiceTypes)
            {
                AssertServiceCountEquals(services, serviceType.Key, serviceType.Value.Length + 1);

                foreach (var implementationType in serviceType.Value)
                {
                    AssertContainsSingle(services, serviceType.Key, implementationType);
                }
            }
        }
Пример #2
0
        public void AddMvcServicesTwice_DoesNotAddDuplicates()
        {
            // Arrange
            var services = new ServiceCollection();

            // Act
            MvcServiceCollectionExtensions.AddMvcServices(services);
            MvcServiceCollectionExtensions.AddMvcServices(services);

            // Assert
            var singleRegistrationServiceTypes = SingleRegistrationServiceTypes;

            foreach (var service in services)
            {
                if (singleRegistrationServiceTypes.Contains(service.ServiceType))
                {
                    // 'single-registration' services should only have one implementation registered.
                    AssertServiceCountEquals(services, service.ServiceType, 1);
                }
                else
                {
                    // 'multi-registration' services should only have one *instance* of each implementation registered.
                    AssertContainsSingle(services, service.ServiceType, service.ImplementationType);
                }
            }
        }
Пример #3
0
        public void WithControllersAsServices_ScansControllersFromSpecifiedAssemblies()
        {
            // Arrange
            var collection      = new ServiceCollection();
            var assemblies      = new[] { GetType().Assembly };
            var controllerTypes = new[] { typeof(ControllerTypeA), typeof(TypeBController) };

            // Act
            MvcServiceCollectionExtensions.WithControllersAsServices(collection, assemblies);

            // Assert
            var services = collection.ToList();

            Assert.Equal(4, services.Count);
            Assert.Equal(typeof(ControllerTypeA), services[0].ServiceType);
            Assert.Equal(typeof(ControllerTypeA), services[0].ImplementationType);
            Assert.Equal(ServiceLifetime.Transient, services[0].Lifetime);

            Assert.Equal(typeof(TypeBController), services[1].ServiceType);
            Assert.Equal(typeof(TypeBController), services[1].ImplementationType);
            Assert.Equal(ServiceLifetime.Transient, services[1].Lifetime);


            Assert.Equal(typeof(IControllerActivator), services[2].ServiceType);
            Assert.Equal(typeof(ServiceBasedControllerActivator), services[2].ImplementationType);
            Assert.Equal(ServiceLifetime.Transient, services[2].Lifetime);

            Assert.Equal(typeof(IControllerTypeProvider), services[3].ServiceType);
            var typeProvider = Assert.IsType <FixedSetControllerTypeProvider>(services[3].ImplementationInstance);

            Assert.Equal(controllerTypes, typeProvider.ControllerTypes.OrderBy(c => c.Name));
            Assert.Equal(ServiceLifetime.Singleton, services[3].Lifetime);
        }
        // This method gets called by the runtime. Use this method to add services to the container
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvcCore()
            .AddAuthorization()
            .AddJsonFormatters();

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme =
                    JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme =
                    JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(o =>
            {
                o.Authority            = "http://localhost:55517/";
                o.Audience             = "scope.readAccess";
                o.RequireHttpsMetadata = false;
            });

            MvcXmlMvcBuilderExtensions.AddXmlSerializerFormatters(MvcServiceCollectionExtensions.AddMvc(services, (Action <MvcOptions>)(options => options.FormatterMappings.SetMediaTypeMappingForFormat("js", MediaTypeHeaderValue.Parse("application/json").ToString()))));
            Environment.SetEnvironmentVariable("AWS_PROFILE_NAME", Configuration.GetValue <string>("AppSettings:ProfileName"));
            Environment.SetEnvironmentVariable("AWS_ACCESS_KEY_ID", Configuration.GetValue <string>("AppSettings:AccessKey"));
            Environment.SetEnvironmentVariable("AWS_SECRET_ACCESS_KEY", Configuration.GetValue <string>("AppSettings:SecretKey"));
            Environment.SetEnvironmentVariable("AWS_REGION", Configuration.GetValue <string>("AppSettings:Region"));
        }
Пример #5
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            MvcServiceCollectionExtensions.AddMvc(services);

            services.AddZzHttpContextAccessor();

            services.AddControllers();

            services.AddZzMvc();

            services.AddDbContext();

            // 3.1 中需要升级 EntityFrameworkCore 相关版本
            services.AddEntityFrameworkSqlServer();
            services.AddEntityFrameworkProxies();

            //services.AddCompositeFileProvider();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo {
                    Title = "ZzConner API", Version = "v1"
                });
            });
        }
Пример #6
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <ApiBehaviorOptions>(options =>
            {
                options.SuppressModelStateInvalidFilter = true;
            });

            services.UseTransactionsManager(this.Configuration, this.m_LoggerFactory);

            MvcCoreMvcBuilderExtensions.SetCompatibilityVersion(MvcServiceCollectionExtensions.AddMvc(services), (CompatibilityVersion)1);
        }
Пример #7
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(corsOptions => {
                corsOptions.AddPolicy("AllowAllOriginsForAngularOops",
                                      builder =>
                {
                    builder.AllowAnyOrigin();
                });
            });

            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddScoped <WLMDbContext, WLMDbContext>();

            //SEARCHED "AddMvc() api" in google.

            //DELETED below code line.
            //services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            //ADD below code

            //MVCOptions.EnableEndpointRouting = false; https://apisof.net/catalog/Microsoft.AspNetCore.Mvc.MvcOptions
            //Startup.cs(47,13): error CS0103: The name 'MVCOptions' does not exist in the current context [C:\Users\ydvsjq\Desktop\Projects\Allocator3\Server\Server.csproj]
            //then few more errors which got me to write below code.

            //ADD 1 try - failed
            //MvcOptions mvcOptions = new MvcOptions();
            //mvcOptions.EnableEndpointRouting = false;
            //MvcServiceCollectionExtensions.AddMvc(services,mvcOptions);

            //ERR:
            //Startup.cs(55,60): error CS1503: Argument 2: cannot convert from 'Microsoft.AspNetCore.Mvc.MvcOptions' to 'System.Action<Microsoft.AspNetCore.Mvc.MvcOptions>' [C:\Users\ydvsjq\Desktop\Projects\Allocator3\Server\Server.csproj]
            //ADD 2 try - succeeded

            //Action<MvcOptions> myAction = new Action<MvcOptions>()
            Action <MvcOptions> myAction = (MvcOptions) => { MvcOptions.EnableEndpointRouting = false; };

            MvcServiceCollectionExtensions.AddMvc(services, myAction);

            //wow donwe

            /*Build succeeded.
             * C:\Prgm\dotnet\sdk\3.0.100\Sdks\Microsoft.NET.Sdk\targets\Microsoft.NET.Sdk.DefaultItems.targets(149,5): warning NETSDK1080: A PackageReference to Microsoft.AspNetCore.App is not necessary when targeting .NET Core 3.0 or higher. If Microsoft.NET.Sdk.Web is used, the shared framework will be referenced automatically. Otherwise, the PackageReference should be replaced with a FrameworkReference. [C:\Users\ydvsjq\Desktop\Projects\Allocator3\Server\Server.csproj]
             * C:\Prgm\dotnet\sdk\3.0.100\Sdks\Microsoft.NET.Sdk\targets\Microsoft.NET.Sdk.DefaultItems.targets(149,5): warning NETSDK1080: A PackageReference to Microsoft.AspNetCore.App is not necessary when targeting .NET Core 3.0 or higher. If Microsoft.NET.Sdk.Web is used, the shared framework will be referenced automatically. Otherwise, the PackageReference should be replaced with a FrameworkReference. [C:\Users\ydvsjq\Desktop\Projects\Allocator3\Server\Server.csproj]
             * Startup.cs(67,56): warning CS0618: 'IHostingEnvironment' is obsolete: 'This type is obsolete and will be removed in a future version. The recommended alternative is Microsoft.AspNetCore.Hosting.IWebHostEnvironment.' [C:\Users\ydvsjq\Desktop\Projects\Allocator3\Server\Server.csproj]
             * 3 Warning(s)
             * 0 Error(s)
             */
        }
Пример #8
0
        public static IServiceCollection AddControllers(this IServiceCollection services)
        {
            MvcServiceCollectionExtensions.AddControllers(services)
            .AddNewtonsoftJson(options =>
            {
                options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
                options.SerializerSettings.ContractResolver  = new CamelCasePropertyNamesContractResolver();
            })
            .AddFluentValidation(config => config.RegisterValidatorsFromAssemblyContaining <Startup>());

            return(services);
        }
Пример #9
0
        public void MultiRegistrationServiceTypes_AreRegistered_MultipleTimes()
        {
            // Arrange
            var services = new ServiceCollection();
            var multiRegistrationServiceTypes = MutliRegistrationServiceTypes;

            // Act
            MvcServiceCollectionExtensions.AddMvcServices(services);
            MvcServiceCollectionExtensions.AddMvcServices(services);

            // Assert
            foreach (var serviceType in multiRegistrationServiceTypes)
            {
                AssertServiceCountEquals(services, serviceType, 2);
            }
        }
Пример #10
0
        public void SingleRegistrationServiceTypes_AreNotRegistered_MultipleTimes()
        {
            // Arrange
            var services = new ServiceCollection();
            var multiRegistrationServiceTypes = MutliRegistrationServiceTypes;

            // Act
            MvcServiceCollectionExtensions.AddMvcServices(services);
            MvcServiceCollectionExtensions.AddMvcServices(services);

            // Assert
            var singleRegistrationServiceTypes = services
                                                 .Where(serviceDescriptor => !multiRegistrationServiceTypes.Contains(serviceDescriptor.ServiceType))
                                                 .Select(serviceDescriptor => serviceDescriptor.ServiceType);

            foreach (var singleRegistrationType in singleRegistrationServiceTypes)
            {
                AssertServiceCountEquals(services, singleRegistrationType, 1);
            }
        }
Пример #11
0
        public void SingleRegistrationServiceTypes_AreNotRegistered_MultipleTimes()
        {
            // Arrange
            var services = new ServiceCollection();

            // Register a mock implementation of each service, AddMvcServices should not replace it.
            foreach (var serviceType in SingleRegistrationServiceTypes)
            {
                var mockType = typeof(Mock <>).MakeGenericType(serviceType);
                services.Add(ServiceDescriptor.Transient(serviceType, mockType));
            }

            // Act
            MvcServiceCollectionExtensions.AddMvcServices(services);

            // Assert
            foreach (var singleRegistrationType in SingleRegistrationServiceTypes)
            {
                AssertServiceCountEquals(services, singleRegistrationType, 1);
            }
        }
Пример #12
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            LoaderExtensions.OnConfigureServicesBeforeAddMvc(services);
            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy", builder =>
                {
                    builder.AllowAnyMethod()
                    .AllowAnyHeader()
                    .WithOrigins("*")
                    .WithMethods("*")
                    .WithHeaders("*")
                    .DisallowCredentials();
                });
            });
            IMvcBuilder mvcBuilder = MvcServiceCollectionExtensions.AddMvc(services).AddNewtonsoftJson();

            //services.Configure<MvcOptions>(options =>
            //{
            //    options.Filters.Add(new AuthorizeFilter("CorsPolicyAll"));
            //});
            services.AddControllers(mvcOtions =>
            {
                mvcOtions.EnableEndpointRouting = false;
            });
            mvcBuilder.SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
            services.AddScoped <IDataBaseMain, DataBaseMain>();
            services.AddScoped <IDataBaseIs4, DataBaseIs4>();
            LoaderExtensions.OnConfigureServicesAfterAddMvc(services, mvcBuilder, Configuration);
            LoaderExtensions.LoadMvc(mvcBuilder, GlobalSettingsApp.CurrentAppDirectory);
            LoaderExtensions.OnInitBackendService(services);

            ApplicationContainer = AutoFac.Init(DataBaseName.MySql, cb =>
            {
                cb.Populate(services);
            });
            return(new AutofacServiceProvider(ApplicationContainer));
        }
Пример #13
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //Dependency Injection
            MvcServiceCollectionExtensions.AddMvc(services);

            //Add JWTSettings into the service collection for dependency injection.
            JWTSettings jwtSettings = GetJWTSettings();

            services.AddSingleton <JWTSettings>(jwtSettings);
            services.AddSingleton <EncSettings>(GetEncSettings());

            //Configure Authentication to use JwtBearer and set the Allowed parameters.
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = "JwtBearer";
                options.DefaultChallengeScheme    = "JwtBearer";
            })
            .AddJwtBearer("JwtBearer", jwtBearerOptions =>
            {
                jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(jwtSettings.Key)),
                    ValidateIssuer           = true,
                    ValidIssuer = jwtSettings.Issuer,

                    ValidateAudience = true,
                    ValidAudience    = jwtSettings.Audience,

                    ValidateLifetime = true,
                    ClockSkew        = TimeSpan.Zero
                };
            });
            //Add Claim based Authorization (NOTE; Claim Type And Claim Value and BOTH CASE SENSITIVE)
            services.AddAuthorization(config =>
            {
                var allClaims = Enum.GetValues(typeof(EClaimTypes));
                foreach (var claim in allClaims)
                {
                    config.AddPolicy(claim.ToString(), policyBuilder => policyBuilder.RequireClaim(claim.ToString(), "true"));
                }
            });

            //Compatibility and Cors
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddCors();

            //Add Service Dependency Injection
            string connectionString = Configuration["ShopperHolicDBConnection"];

            services.AddTransient <ISecurityService>(s => new SecurityService(connectionString));
            services.AddTransient <IProductGroupService>(s => new ProductGroupService(connectionString));
            services.AddTransient <ISubGroupService>(s => new SubGroupService(connectionString));
            services.AddTransient <IItemService>(s => new ItemService(connectionString));
            services.AddTransient <ICountryService>(s => new CountryService(connectionString));
            services.AddTransient <ICityService>(s => new CityService(connectionString));
            services.AddTransient <ICityAreaService>(s => new CityAreaService(connectionString));
            services.AddTransient <IAddressService>(s => new AddressService(connectionString));
            services.AddTransient <ICustomerService>(s => new CustomerService(connectionString));
            services.AddTransient <ISupplierService>(s => new SupplierService(connectionString));
            services.AddTransient <IUserService>(s => new UserService(connectionString));
            services.AddTransient <IOrderService>(s => new OrderService(connectionString));
            services.AddTransient <IDeliveryNoteService>(s => new DeliveryNoteService(connectionString));
            services.AddTransient <IInvoiceService>(s => new InvoiceService(connectionString));
            services.AddTransient <IContentService>(s => new ContentService(connectionString));
            services.AddTransient <IRMAService>(s => new RMAService(connectionString));
            services.AddTransient <IReturnNoteService>(s => new ReturnNoteService(connectionString));
            services.AddTransient <ICreditNoteService>(s => new CreditNoteService(connectionString));
        }
Пример #14
0
 public void ConfigureServices(IServiceCollection services)
 {
     MvcCoreMvcBuilderExtensions.SetCompatibilityVersion(MvcServiceCollectionExtensions.AddMvc(services), (CompatibilityVersion)1);
 }