public void Registertypes <TContext, TUser, TRole, TKey>(ContainerBuilder builder, IModule repositoryModule, Action <IMapperConfigurationExpression> mapperExpression) where TContext : IdentityDbContext <TUser, TRole, TKey> where TUser : IdentityUser <TKey> where TRole : IdentityRole <TKey> where TKey : IEquatable <TKey> { var mapper = MapperConfigurator.Configure(mapperExpression); builder.RegisterInstance(mapper).As <IMapper>(); builder.RegisterModule(repositoryModule); builder.RegisterType <HttpContextAccessor>().As <IHttpContextAccessor>().SingleInstance(); builder.RegisterType <UserStore <TUser, TRole, TContext, TKey> >().As <IUserStore <TUser> >().InstancePerDependency(); builder.RegisterType <RoleStore <TRole, TContext, TKey> >().As <IRoleStore <TRole> >().InstancePerDependency(); builder.RegisterType <UserClaimsPrincipalFactory <TUser> >().As <IUserClaimsPrincipalFactory <TUser> >().InstancePerDependency(); builder.RegisterType <UserManager <TUser> >().AsSelf().InstancePerDependency(); builder.RegisterType <RoleManager <TRole> >().AsSelf().InstancePerDependency(); builder.Register(context => new JwtTokenFactory()).As <JwtTokenFactory>().InstancePerDependency(); builder.Register(context => new JwtTokenManager()).As <JwtTokenManager>().InstancePerDependency(); builder.RegisterServices <TUser, TRole, TKey>(); }
static void Main(string[] args) { MapperConfigurator.Configure(); var container = Windsor.Container; Windsor.Initialize(); using (container.BeginScope()) { var service = container.Resolve <IProductManager>(); Console.WriteLine($"Вводи товар бля"); string name = Console.ReadLine(); service.AddProduct(new DTO.ProductDTO { Name = name }); Console.WriteLine($"Добавлен новый товар: {name}"); // Получение всех товаров var allAdverts = service.GetAllProducts(); foreach (var advert in allAdverts) { Console.WriteLine(advert.Id); Console.WriteLine(advert.Name); } //Получение по ИД Console.WriteLine($"Получить по ИД"); int ID = int.Parse(Console.ReadLine()); var GetById = service.GetProductId(ID); Console.WriteLine($"Товар по ИД: {GetById.Name}"); //// Удаление по ИД //Console.WriteLine($"Удалить"); //int DeleteId = int.Parse(Console.ReadLine()); //service.DeleteProduct(DeleteId); //// Получение всех товаров после удаления //var allAdvertss = service.GetAllProducts(); //foreach (var advert in allAdvertss) //{ // Console.WriteLine(advert.Name); //} //Console.ReadKey(); Console.WriteLine($"Обновление по ИД"); string name1 = Console.ReadLine(); service.EditProduct(new DTO.ProductDTO { Id = 1, Name = name1 }); var allAdvertss = service.GetAllProducts(); foreach (var advert in allAdvertss) { Console.WriteLine(advert.Id); Console.WriteLine(advert.Name); } Console.ReadKey(); } }
public void Constructor_StateUnderTest_NullParameter() { // Act var unitUnderTest = new MapperConfigurator <TestProfile>(null); // Assert unitUnderTest.ShouldNotBeNull(); unitUnderTest.Configuration.ShouldNotBeNull(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { 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.AddDbContext <GiftExchangerContext>(options => options.UseSqlServer( Configuration.GetConnectionString(env.IsDevelopment() ? "DefaultConnection" : "DeployConnectionString"))); services.AddMemoryCache(); services.AddIdentity <UserGE, IdentityRole>(opt => { opt.Password.RequireDigit = false; opt.Password.RequireNonAlphanumeric = false; opt.Password.RequireLowercase = false; opt.Password.RequireUppercase = false; opt.Password.RequiredLength = 4; opt.Password.RequiredUniqueChars = 2; opt.User.RequireUniqueEmail = false; opt.Lockout.MaxFailedAccessAttempts = 10; opt.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(10); }).AddRoles <IdentityRole>() .AddEntityFrameworkStores <GiftExchangerContext>(); services.AddAuthentication(); services.AddScoped <IUserClaimsPrincipalFactory <UserGE>, UserClaimsPrincipalFactory <UserGE, IdentityRole> >(); services.AddMvc( opt => { opt.Filters.Add <AutoValidateAntiforgeryTokenAttribute>(); opt.EnableEndpointRouting = false; }) .SetCompatibilityVersion(CompatibilityVersion.Version_3_0); services.AddControllersWithViews().AddRazorRuntimeCompilation(); services.AddRazorPages(); var profile = new MapperConfigurator(); var mappingConfig = new MapperConfiguration(mc => { mc.AddProfile(profile); }); IMapper mapper = mappingConfig.CreateMapper(); services.AddSingleton(mapper); services.AddScoped(typeof(IRepository <>), typeof(DbRepository <>)); services.AddTransient <IUserService, UserService>(); services.AddTransient <IStatisticsService, StatisticsService>(); services.AddTransient <ITransferService, TransferService>(); }
public override void Initialize() { base.Initialize(); CreatableTypes() .EndingWith("Service") .AsInterfaces() .RegisterAsLazySingleton(); Mvx.IoCProvider.RegisterSingleton(MapperConfigurator.InitializeProfiles().CreateMapper()); RegisterAppStart <HomeViewModel>(); }
public void ConfigureServices(IServiceCollection services) { BsonClassMapper.Tune(); services .AddSingleton(Options) .AddSingleton(MapperConfigurator.CreateMapper()) .AddMongo(Options.Mongo) .AddScoped <OrganizationRepository>() .AddScoped <DaDataOrgService>() .AddScoped <DaDataOrgRepository>(); services .AddHealthChecks(); services .AddVaultCors() .AddVaultAuthorization() .AddHttpClient <DaDataClient>(x => { x.BaseAddress = new Uri(Options.DaDataServer); x.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Token", Options.DaDataToken); }); services .Configure <MvcJsonOptions>(o => { o.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); o.SerializerSettings.Converters.Add(new StringEnumConverter()); }) .AddMvcCore() .AddFormatterMappings() .AddDataAnnotations() .AddJsonFormatters() .AddApiExplorer() .SetCompatibilityVersion(CompatibilityVersion.Version_2_2) .AddMvcOptions(o => o.Filters.Add(new ExceptionStatusCodeFilter <VaultNotFoundException>(404, 10))); services .AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme) .AddIdentityServerAuthentication(options => { options.Authority = "https://auth.site.com"; options.ClaimsIssuer = "https://auth.site.com"; options.SupportedTokens = SupportedTokens.Jwt; options.EnableCaching = true; }); }
static void Main(string[] args) { WindsorWrapper.Init(); MapperConfigurator.Configure(); var container = WindsorWrapper.Container; using (WindsorWrapper.Container.BeginScope()) { var service = container.Resolve <IAdvertService>(); var allAdverts = service.GetAllAdverts(); foreach (var advert in allAdverts) { Console.WriteLine($"{advert.Title, 30} | { advert.Cities.FirstOrDefault()?.Name, 15 } |" + $" {advert.Price} {(advert.Price.HasValue ? "руб." : string.Empty)}"); } } Console.ReadLine(); }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpControllerActivator), new WindsorWebApiControllerActivator(WindsorWrapper.Container)); //Инициализация IOC с прокидыванием туда инсталлера контроллера. Этот IOC собирает в себе все сущности приложения WindsorWrapper.Init(new ControllerInstaller(Assembly.GetExecutingAssembly())); //Чтобы сделать IOC доступным в любой точке приложения, передаем его общедоступной сущности CommonContainer CommonContainer.CommonContainer.Initialize(WindsorWrapper.Container); MapperConfigurator.Configure(); //Создание фабрики Windsor, позволяющей делать внедрение зависимостей через конструктор WindsorControllerFactory controllerFactory = new WindsorControllerFactory(WindsorWrapper.Container.Kernel); //замена дефолтной фабрики контроллеров на фабрику Windsor ControllerBuilder.Current.SetControllerFactory(controllerFactory); }
protected void Application_Start() { GlobalConfiguration.Configure(WebApiConfig.Register); MapperConfigurator.Configure(); AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); GlobalConfiguration.Configuration.Services.Replace( typeof(IHttpControllerActivator), new WindsorApiControllerActivator(GlobalContainer.Container)); // вот тут GlobalContainer.Initialize(new DatabasesInstaller()); GlobalContainer.Initialize(new RepositoriesInstaller()); GlobalContainer.Initialize(new ServicesInstaller()); GlobalContainer.Initialize(new ControllersInstaller(Assembly.GetExecutingAssembly())); var controllerFactory = new WindsorControllerFactory(GlobalContainer.Container.Kernel); ControllerBuilder.Current.SetControllerFactory(controllerFactory); }
public void Setup() { MapperConfigurator.Configure(); #region Города var sevastopol = new City { Id = 1, Name = "Севастополь" }; var simferopol = new City { Id = 2, Name = "Симферополь" }; var kerch = new City { Id = 3, Name = "Керчь" }; var yalta = new City { Id = 4, Name = "Ялта" }; var moscow = new City { Id = 5, Name = "Москва" }; #endregion #region Пользователи var user1 = new User { Id = 1, UserName = "******", Password = "******" }; var user2 = new User { Id = 2, UserName = "******", Password = "******" }; var user3 = new User { Id = 3, UserName = "******", Password = "******" }; #endregion #region Объявления var testAdvert1 = new Advert { Id = 1, Title = "Продам гараж", Text = "Продаётся гараж, дорого, 5км от МКАД", Cities = new List <City> { moscow }, Price = 300000, PublishDate = DateTime.UtcNow.AddDays(-5), ViewsCount = 10000, }; var testAdvert2 = new Advert { Id = 2, Title = "Продам гараж", Text = "Продаётся гараж, недорого, 20км от МКАД", Cities = new List <City> { moscow }, Price = 50000, PublishDate = DateTime.UtcNow, ViewsCount = 10000, }; var testAdvert3 = new Advert { Id = 3, Title = "Грузоперевозки Газель", Text = "Грузоперевозки Газель 4.2м. Переезды, трезвые грузчики", Cities = new List <City> { sevastopol, simferopol, kerch, yalta }, PublishDate = DateTime.UtcNow, ViewsCount = 1000 }; var testAdvert4 = new Advert { Id = 4, Title = "Куртка норковая вязаная", Text = "Куртка норковая вязания без подклада, на замке б/у, подойдет и на 44 и 48 размер.", Cities = new List <City> { sevastopol, yalta }, PublishDate = DateTime.UtcNow.AddDays(-20), Price = 8000, ViewsCount = 650 }; var testAdvert5 = new Advert { Id = 5, Title = "Mitsubishi Outlander, 2016", Text = "Новая машина. Не бита не сколов .машина стоит ждёт .нового хозяина.торг", PublishDate = DateTime.UtcNow.AddDays(-1), Price = 1250000, ViewsCount = 105 }; var testAdvert6 = new Advert { Id = 6, Title = "Стрижка собак и кошек. Выезд", Text = "Стоимость стрижки зависит от породы и характера питомца. Выезд к Вам на дом.", Cities = new List <City> { sevastopol }, PublishDate = DateTime.UtcNow.AddDays(-7), ViewsCount = 25 }; var testAdvert7 = new Advert { Id = 7, Title = "Сапоги", Text = "Сапоги на меху, тёплые, комфортные для ноги. Размер 28. Состояние отличное, носили 3 месяца всего.", Cities = new List <City> { simferopol }, PublishDate = DateTime.Now.AddDays(-2), Price = 1600, ViewsCount = 250 }; #endregion _testAdverts = new List <Advert> { testAdvert1, testAdvert2, testAdvert3, testAdvert4, testAdvert5, testAdvert6, testAdvert7 }; _testAdvertDtos = Mapper.Map <IEnumerable <Advert>, List <AdvertDto> >(_testAdverts); _testUsers = new List <User> { user1, user2, user3 }; _testCities = new List <City> { sevastopol, simferopol, moscow, yalta, kerch }; _advertRepositoryMock = new Mock <IRepository <Advert> >(); _advertService = new AdvertService(_advertRepositoryMock.Object); }
public MapperTests() { this.mockRepository = new MockRepository(MockBehavior.Strict); mapperConfigurator = new MapperConfigurator <TestProfile>(new TestProfile()); }
public static void Main(string[] args) { MapperConfigurator.Configure(); CreateHostBuilder(args).Build().Run(); }