Пример #1
0
        public static void Register(Container container)
        {
            container.Register(typeof (IQueryHandler<,>), new[] {typeof (IQueryHandler<,>).Assembly});
            container.Register(typeof (ICommandHandler<,>), new[] {typeof (ICommandHandler<,>).Assembly});

            container.RegisterCollection(typeof (IHyperMediaState), typeof (IHyperMediaState).Assembly);
            container.Register<IBoardState, BoardState>();
            container.Register<IBoardTaskState, BoardTaskState>();
            container.Register<IBoardColumnState, BoardColumnState>();

            container.Register<ISlugService, SlugService>();

            container.Register<ICommandDispatcher, CommandDispatcher>();
            container.Register<IQueryDispatcher, QueryDispatcher>();
            container.Register<ILinkFactory, LinkFactory>();
            container.Register<IHyperMediaFactory, HyperMediaFactory>();
            container.Register<IMappingService, MappingService>();

            container.RegisterWebApiRequest<IDataContext, DataContext>();

            container.RegisterWebApiControllers(GlobalConfiguration.Configuration);
            container.EnableHttpRequestMessageTracking(GlobalConfiguration.Configuration);
            container.RegisterSingleton<IRequestMessageProvider>(new RequestMessageProvider(container));

            container.Register<IValidator<Board>, BoardValidator>();
            container.Register<IValidator<BoardColumn>, BoardColumnValidator>();
            container.Register<IValidator<BoardTask>, BoardTaskValidator>();

            container.Verify();

            GlobalConfiguration.Configuration.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container);
        }
Пример #2
0
        public void Configuration(IAppBuilder app)
        {
            var container = new Container();

            container.Options.DefaultScopedLifestyle = new ExecutionContextScopeLifestyle();
            InitializeContainer(container);
            container.Verify();

            app.Use(async(context, next) =>
            {
                using (container.BeginExecutionContextScope())
                {
                    await next();
                }
            });

            var config = new HttpConfiguration();

            ConfigureOAuth(app);

            //config.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(this.Container);

            WebApiConfig.Register(config);
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            //app.UseWebApi(config);
        }
        private static void InitializeContainer(Container container)
        {
            container.Register<ICardRepository, CardRepository>();

            // For instance:
            // container.Register<IUserRepository, SqlUserRepository>(Lifestyle.Scoped);
        }
Пример #4
0
 private static void Bootstrap()
 {
     container = new SimpleInjector.Container();
     container.Register <IUsersService, UserServices>();
     container.Register <Iunitofwork, SampleContext>();
     container.Register <frm_AddEdit>();
 }
        static NewExpression BuildNewExpression(Container container,
                                                ConstructorInfo constructor,
                                                ParameterExpression[] funcParameterExpression)
        {
            var ctorParameters     = constructor.GetParameters();
            var ctorParameterTypes = ctorParameters.Select(p => p.ParameterType).ToArray();
            var funcParameterTypes = funcParameterExpression.Select(p => p.Type).ToArray();

            var funcParametersIndex = IndexOfSubCollection(ctorParameterTypes, funcParameterTypes);

            if (funcParametersIndex == -1)
            {
                throw new ActivationException(
                          $"The constructor of type {constructor.DeclaringType.FullName} did not contain the sequence of the following " +
                          $"constructor parameters: {string.Join(", ", funcParameterTypes.Select(t => t.Name))}.");
            }

            var firstCtorParameterExpressions = ctorParameterTypes
                                                .Take(funcParametersIndex)
                                                .Select(type => container.GetRegistration(type, true).BuildExpression());

            var lastCtorParameterExpressions = ctorParameterTypes
                                               .Skip(funcParametersIndex + funcParameterTypes.Length)
                                               .Select(type => container.GetRegistration(type, true).BuildExpression());

            var expressions = firstCtorParameterExpressions
                              .Concat(funcParameterExpression)
                              .Concat(lastCtorParameterExpressions)
                              .ToArray();

            return(Expression.New(constructor, expressions));
        }
Пример #6
0
        public async Task CreateSimpleHttpServer_RoutingWithHttpAttributes_ReplaceService()
        {
            using (var httpServer = new OwinHttpServer(new UriBuilder("http://localhost:5001/")))
            {
                var container = new SimpleInjector.Container();

                var resetEvent = new ManualResetEventSlim();

                RegisterExceptionLogger(ref container, resetEvent);

                httpServer.AddDependencyResolver(() => new SimpleInjectorWebApiDependencyResolver(container))
                .SetHttpRouteAttributes()
                .ReplaceService <IExceptionLogger>((serviceResolver) =>
                {
                    IExceptionLogger exceptionLogger = serviceResolver.GetService(typeof(IExceptionLogger)) as IExceptionLogger;
                    return(exceptionLogger);
                }).TryStart();

                HttpClient client = new HttpClient();
                client.BaseAddress = new Uri("http://localhost:5001/");

                var result = await client.GetAsync($"/Device/state/{1}?active=false");

                resetEvent.Wait();

                Assert.Equal(HttpStatusCode.InternalServerError, result.StatusCode);
            }
        }
        public void SetUp()
        {
            container = new Container();
            container.RegisterAsEasyNetQContainerFactory();

            bus = new MockBuilder().Bus;
        }
        public static void Initialize()
        {
            var container = new Container();
            container.Options.DefaultScopedLifestyle = new WebRequestLifestyle();

            // Chamada dos módulos do Simple Injector
            InitializeContainer(container);

            // Necessário para registrar o ambiente do Owin que é dependência do Identity
            // Feito fora da camada de IoC para não levar o System.Web para fora
            container.RegisterPerWebRequest(() =>
            {
                if (HttpContext.Current != null && HttpContext.Current.Items["owin.Environment"] == null && container.IsVerifying())
                {
                    return new OwinContext().Authentication;
                }
                return HttpContext.Current.GetOwinContext().Authentication;

            });

            container.RegisterMvcControllers(Assembly.GetExecutingAssembly());

            container.Verify();

            DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
        }
Пример #9
0
 public MessageChannel(Container container, RabbitMQServer server, ICommandDiscovery commandDiscovery, IEventDiscovery eventDiscovery)
 {
     _container = container;
     _server = server;
     _commandDiscovery = commandDiscovery;
     _eventDiscovery = eventDiscovery;
 }
Пример #10
0
        private static void BenchSimpleInjector()
        {
            var services = new ServiceCollection();

            services.AddScoped <IValueProvider, ValueProvider>();
            services.AddLogging();

            var container = new SimpleInjector.Container();

            services.AddSimpleInjector(container);

            services.BuildServiceProvider().UseSimpleInjector(container);

            Launch("SimpleInjector (ThreadScoped)", (i) =>
            {
                using (var serviceScope = ThreadScopedLifestyle.BeginScope(container))
                {
                    var valueProvider = serviceScope.GetRequiredService <IValueProvider>();
                    valueProvider.GetValue(i);
                }
            });

            Launch("SimpleInjector (AsyncScopedLifestyle)", (i) =>
            {
                using (var serviceScope = AsyncScopedLifestyle.BeginScope(container))
                {
                    var valueProvider = serviceScope.GetRequiredService <IValueProvider>();
                    valueProvider.GetValue(i);
                }
            });
        }
        private static void InitSiteContainer(Container container)
        {
            container.Register<Fx.Domain.Account.IService.IAccountService, Fx.Domain.Account.UserAccountService>();
            container.Register<Fx.Domain.FxSite.IService.IChannelService, Fx.Domain.FxSite.ChannelService>();
            container.Register<Fx.Domain.FxSite.IService.ISite, Fx.Domain.FxSite.SiteService>();

            container.Register<Fx.Domain.FxSite.IService.IGoods, Fx.Domain.FxSite.GoodsService>();
            container.Register<Fx.Domain.FxSite.IService.ICar, Fx.Domain.FxSite.CarService>();
            container.Register<Fx.Domain.FxSite.IService.IHouse, Fx.Domain.FxSite.HouseService>();

            //FxGoods
            container.Register<Fx.Domain.FxGoods.IService.ITransferGoods, Fx.Domain.FxGoods.FxTransferGoodService>();
            container.Register<Fx.Domain.FxGoods.IService.IBuyGoods, Fx.Domain.FxGoods.FxBuyGoodsService>();

            //FxCar
            container.Register<Fx.Domain.FxCar.IService.ITransferCar, Fx.Domain.FxCar.FxTransferCarService>();
            container.Register<Fx.Domain.FxCar.IService.IBuyCar, Fx.Domain.FxCar.FxBuyCarService>();

            //FxHouse
            container.Register<Fx.Domain.FxHouse.IService.ITransferHouse, Fx.Domain.FxHouse.FxTransferHouseService>();
            container.Register<Fx.Domain.FxHouse.IService.IBuyHouse, Fx.Domain.FxHouse.FxBuyHouseService>();

            //�������
            container.RegisterSingle<Fx.Infrastructure.Caching.ICacheManager, Fx.Infrastructure.Caching.CacheManager>();
        }
Пример #12
0
        private static void MapRoutes(HttpConfiguration config, Container container)
        {
            config.Routes.MapHttpRoute(
                name: "QueryApi",
                routeTemplate: "api/queries/{query}",
                defaults: new { },
                constraints: new { },
                handler: new QueryDelegatingHandler(
                    handlerFactory: container.GetInstance,
                    queryTypes: Bootstrapper.GetKnownQueryTypes()));

            config.Routes.MapHttpRoute(
                name: "CommandApi",
                routeTemplate: "api/commands/{command}",
                defaults: new { },
                constraints: new { },
                handler: new CommandDelegatingHandler(
                    handlerFactory: container.GetInstance,
                    commandTypes: Bootstrapper.GetKnownCommandTypes()));

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional });
        }
Пример #13
0
        public static void Register(Container container)
        {
            container.RegisterOpenGeneric(typeof(IRepository<>), typeof(Repository<>));

            // Single services
            container.Register<IContext, DefaultContext>();
            container.Register<ICommandPersister, DefaultCommandPersister>();
            container.Register<ICommandSerializer, NewtonsoftCommandSerializer>();
            //container.Register<ICommandSerializer, JilCommandSerializer>();

            AddInterfaceForEachDerivedType(container, typeof(TableBase), typeof(ITableBeforeSave<>));
            AddInterfaceForEachDerivedType(container, typeof(TableBase), typeof(ITableAfterSave<>));

            AddInterfaceForEachDerivedType(container, typeof(CommandBase), typeof(ICommandBeforeProcess<>));
            AddInterfaceForEachDerivedType(container, typeof(CommandBase), typeof(ICommandBeforeSave<>));
            AddInterfaceForEachDerivedType(container, typeof(CommandBase), typeof(ICommandAfterSave<>));

            // default persister
            container.RegisterOpenGeneric(typeof(ICommandSave<>), typeof(DefaultSaver<>));

            // override persisters
            container.Options.AllowOverridingRegistrations = true;

            //container.RegisterOpenGeneric(typeof(InsertCommandFor<>), typeof(SimpleCommandsDefaultSaver<>));
            //container.RegisterManyForOpenGeneric(typeof(ICommandSave<>), AppDomain.CurrentDomain.GetAssemblies());
            //container.RegisterManyForOpenGeneric(typeof(ICommandSave<>).MakeGenericType(typeof(InsertCommandFor<>)), AppDomain.CurrentDomain.GetAssemblies());
            /*
            ReplaceInterfaceForEachDerivedType(container, 
                typeof(SimpleCommand<>), 
                typeof(ICommandSave<>).MakeGenericType(typeof(InsertCommandFor<>))
                );*/

            //RegisterAllPersisters();

        }
Пример #14
0
        protected void Application_Start()
        {
            log4net.Config.XmlConfigurator.Configure();

            var container = new Container();
            container.Options.DefaultScopedLifestyle = new WebApiRequestLifestyle();

            container.Register<IUserService, UserService>(Lifestyle.Scoped);
            container.Register<IUserRepository, UserHibernateRepository>(Lifestyle.Scoped);
            container.Register<IAssetService, AssetService>(Lifestyle.Scoped);
            container.Register<IAssetViewService, AssetViewService>(Lifestyle.Scoped);
            container.Register<IAssetRepository, AssetHibernateRepository>(Lifestyle.Scoped);
            container.Register<ITokenService, TokenService>(Lifestyle.Scoped);
            container.Register<ITokenRepository, TokenHibernateRepository>(Lifestyle.Scoped);

            container.RegisterWebApiControllers(GlobalConfiguration.Configuration);

            container.Verify();

            GlobalConfiguration.Configuration.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container);

            // Web API configuration and services

            // Web API routes
            WebApiConfig.Register(GlobalConfiguration.Configuration);
        }
Пример #15
0
        public void RegisterServices(Container container)
        {
            //Config
            container.RegisterWebApiRequest<IDbSettings>(() => new DbSettings(Constants.ConnectionName));

            //DbContext
            container.RegisterWebApiRequest<IPropertyMatrixContext>(() => new PropertyMatrixContext(container.GetInstance<IDbSettings>()));

            //Services
            container.Register<IPriceRangeService, PriceRangeService>();
            container.Register<IQuoteService, QuoteService>();
            container.Register<IAppointmentService, AppointmentService>();
            container.Register<ISearchService, SearchService>();

            //Data
            container.Register<IPriceRangeRepository, PriceRangeRepository>();
            container.Register<IQuoteRepository, QuoteRepository>();
            container.Register<IAppointmentRepository, AppointmentRepository>();
            container.Register<ISearchRepository, SearchRepository>();

            //Mapping
            container.Register<IMapToExisting<PriceRange, PriceRange>, PriceRangeMapper>();

            //Reference Generator
            container.Register<IReferenceGenerator, CryptographicReferenceGenerator>();

            container.Verify();
        }
Пример #16
0
        static void Main(string[] args)
        {
            Console.WriteLine("DEMO >> DbSet");

            var contenedor = new SimpleInjector.Container();

            contenedor.Register <IConeccion, Coneccion>(Lifestyle.Singleton);
            contenedor.Register <Productos>(Lifestyle.Singleton);

            var productos = contenedor.GetInstance <Productos>();

            var a = productos.Crear();

            a.Descripcion = "Coca cola";
            a.Precio      = 90;

            productos.Agregar(a);
            Pausa();

            a.PonerOferta();
            productos.Actualizar(a);
            Pausa();

            productos.Borrar(a);
            Pausa();

            var ps = productos.Traer("Precio < 90");
        }
Пример #17
0
        // Invoked once at startup to configure your application.
        public void Configuration(IAppBuilder builder)
        {
            var config = new HttpConfiguration();

            // Create the container as usual.
            var container = new Container();

            // Register your types, for instance using the RegisterWebApiRequest
            // extension from the integration package:
            container.RegisterWebApiRequest<IUserRepository, SqlUserRepository>();

            // This is an extension method from the integration package.
            container.RegisterWebApiControllers(config);

            container.Verify();

            config.DependencyResolver =
                new SimpleInjectorWebApiDependencyResolver(container);

            config.MapHttpAttributeRoutes();
            //config.Routes.MapHttpRoute("Default", "", new { controller = "OEmbed" });

            //config.Formatters.XmlFormatter.UseXmlSerializer = true;
            //config.Formatters.Remove(config.Formatters.JsonFormatter);
            ////config.Formatters.Remove(config.Formatters.XmlFormatter);
            // config.Formatters.JsonFormatter.UseDataContractJsonSerializer = true;
            builder.UseWebApi(config);

            //builder.Use(async (context, next) => {
            //    using (container.BeginExecutionContextScope())
            //    {
            //        await next();
            //    }
            //});
        }
Пример #18
0
        // This code configures Web API contained in the class Startup, which is additionally specified as the type
        // parameter in WebApplication.Start
        public void Configuration(IAppBuilder appBuilder)
        {
            // Add SimpeInjector package.
            var container = new Container();
            container.Options.DefaultScopedLifestyle = new WebApiRequestLifestyle();

            // Add SimpleInjector.Integration.WebApi package.
            container.Register<IValuesService, ValuesService>(new WebApiRequestLifestyle());

            // Configure Web API for Self-Host
            // HttpConfiguration located in Microsoft.AspNet.WebApi.Core package.
            HttpConfiguration config = new HttpConfiguration();

            // Add System.Web reference to avoid "Missing ..." error.
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            config.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container);

            // UseWebApi extension method located in Microsoft.AspNet.WebApi.OwinSelfHost package.
            appBuilder.UseWebApi(config);
        }
Пример #19
0
        /// <summary>
        ///   Loads the module into the kernel.
        /// </summary>
        /// <param name="container">The container.</param>
        public void register_components(Container container)
        {
            Log.InitializeWith<Log4NetLog>();

            IConfigurationSettings configuration = new ConfigurationSettings();
            Config.initialize_with(configuration);

            container.Register(() => configuration, Lifestyle.Singleton);

            container.Register<IEventAggregator, EventAggregator>(Lifestyle.Singleton);
            container.Register<IMessageSubscriptionManagerService, MessageSubscriptionManagerService>(Lifestyle.Singleton);
            EventManager.initialize_with(container.GetInstance<IMessageSubscriptionManagerService>);

            container.Register<INotificationSendService, SmtpMarkdownNotificationSendService>(Lifestyle.Singleton);
            container.Register<IMessageService, MessageService>(Lifestyle.Singleton);
            container.Register<IEmailDistributionService, EmailDistributionService>(Lifestyle.Singleton);
            container.Register<IDateTimeService, SystemDateTimeUtcService>(Lifestyle.Singleton);
            container.Register<ICommandExecutor, CommandExecutor>(Lifestyle.Singleton);
            container.Register<IFileSystemService, FileSystemService>(Lifestyle.Singleton);
            container.Register<IFileSystem, DotNetFileSystem>(Lifestyle.Singleton);
            container.Register<IRegularExpressionService, RegularExpressionService>(Lifestyle.Singleton);
            container.Register<INuGetService, NuGetService>(Lifestyle.Singleton);
            container.Register<IPackageValidationService, PackageValidationService>(Lifestyle.Singleton);
            container.Register<ITypeLocator, TypeLocator>(Lifestyle.Singleton);

            RegisterOverrideableComponents(container, configuration);
        }
Пример #20
0
        public override bool OnStart()
        {
            var container = new Container();

            try
            {
                // Building IoC container
                Initialize(container);
                container.Verify();

                // Initializers
                var initializers = new List<IInitializable>
                {
                    container.GetInstance<TraceListenersInitializer>(),
                    container.GetInstance<DiagnosticsInitializer>()
                };
                foreach (IInitializable initializer in initializers)
                {
                    initializer.Initialize();
                }
            }
            catch (Exception e)
            {
                Trace.TraceError("Failed to start BillingSync worker role: {0}", e);
                throw;
            }

            _container = container;


            return base.OnStart();
        }
Пример #21
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            // Allow Any Certificates
            // This should not be the same in Production
            ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;

            // Create the container as usual.
            var container = new Container();
            container.Options.PropertySelectionBehavior = new ImportPropertySelectionBehavior();
            container.Register<IErrorSignaler, ErrorSignaler>(Lifestyle.Singleton);
            container.Register<IHttpClientHelper, HttpClientHelper>(Lifestyle.Singleton);
            container.Register<IConfigurationHelper, ConfigurationHelper>(Lifestyle.Singleton);

            // SI Attributes Dependency Injection
            container.RegisterInitializer<BlogApiAuthorizationAttribute>(a => a.ErrorSignaler = container.GetInstance<ErrorSignaler>());
            container.RegisterInitializer<BlogAuthorizationAttribute>(a => a.ErrorSignaler = container.GetInstance<ErrorSignaler>());

            // This is an extension method from the integration package.
            container.RegisterMvcControllers(System.Reflection.Assembly.GetExecutingAssembly());
            container.RegisterMvcIntegratedFilterProvider();
            container.Verify();

            DependencyResolver.SetResolver(new SimpleInjector.Integration.Web.Mvc.SimpleInjectorDependencyResolver(container));
        }
Пример #22
0
        protected void Application_Start()
        {
            var container = new Container();
            container.Options.DefaultScopedLifestyle = new WebApiRequestLifestyle();

            // Register your types, for instance using the scoped lifestyle:
            container.Register<IUnitOfWork, UnitOfWork>(Lifestyle.Scoped);
            container.Register<IUserManager, UserManager>();
            container.Register<IOrderManagerEx, OrderManagerEx>();

            // This is an extension method from the integration package.
            container.RegisterWebApiControllers(GlobalConfiguration.Configuration);

            container.Verify();

            GlobalConfiguration.Configuration.DependencyResolver =
                new SimpleInjectorWebApiDependencyResolver(container);
            AutoMapperConfig.Configure();
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            log4net.Config.XmlConfigurator.Configure(new FileInfo(Server.MapPath("~/Web.config")));
        }
 /// <summary>
 /// Registers the service locater.
 /// </summary>
 /// <param name="container">The container.</param>
 private void RegisterServiceLocator(Container container)
 {
     try
     {
         container.Register<IPageDataRepository, PageDataRepository>(Lifestyle.Singleton);
         container.Register<IPageItemDataRepository, PageItemDataRepository>(Lifestyle.Singleton);
         container.Register<IEventDataRepository, EventDataRepository>(Lifestyle.Singleton);
         container.Register<IUserInfoDataRepository, UserInfoDataRepository>(Lifestyle.Singleton);
         container.Register<IFavoriteImageDataRepository, FavoriteImageDataRepository>(Lifestyle.Singleton);
         container.Register<IFavoritePageDataRepository, FavoritePageDataRepository>(Lifestyle.Singleton);
         container.Register<IUserImageDataRepository, UserImageDataRepository>(Lifestyle.Singleton);
         container.Register<IBannerDataRepository, BannerDataRepository>(Lifestyle.Singleton);
         container.Register<IBannerItemDataRepository, BannerItemDataRepository>(Lifestyle.Singleton);
         container.Register<IPageBannerDataRepository, PageBannerDataRepository>(Lifestyle.Singleton);
         container.Register<ISplashImageDataRepository, SplashImageDataRepository>(Lifestyle.Singleton);
         container.Register<IHitCounterDataRepository, HitCounterDataRepository>(Lifestyle.Singleton);
         container.Register<IHitCounterDetailDataRepository, HitCounterDetailDataRepository>();
         container.Register<IDeviceRegistryDataRepository, DeviceRegistryDataRepository>(Lifestyle.Singleton);
         container.Register<INotificationLogDataRepository, NotificationLogDataRepository>(Lifestyle.Singleton);
     }
     catch (Exception ex)
     {
         ex.ExceptionValueTracker(container);
     }
 }
Пример #24
0
        public async Task CreateSimpleHttpServer_RoutingWithHttpAttributes_RoutedMiddleware()
        {
            var httpServer = new OwinHttpServer(new UriBuilder("http://localhost:5000/"));

            var container  = new SimpleInjector.Container();
            var resetEvent = new ManualResetEventSlim();

            RegisterManualResetEvent(ref container, resetEvent);

            httpServer.AddDependencyResolver(() => new SimpleInjectorWebApiDependencyResolver(container))
            .SetHttpRouteAttributes()
            .AddMiddleware((iocResolver) =>
            {
                var _resetEvent = iocResolver.GetService(typeof(ManualResetEventSlim));

                return(new OwinMiddlewareRegistration(typeof(TestOwinMiddleware), new object[] { _resetEvent }, "/WebSockets"));
            });

            HttpClient client = CreateHttpClient(CreateTestServer(httpServer));

            client.BaseAddress = new Uri("http://localhost");

            var result = await client.GetAsync($"/WebSockets/");

            resetEvent.Wait();

            Assert.Equal(HttpStatusCode.Redirect, result.StatusCode);
        }
Пример #25
0
 public void RegisterServices(Container container)
 {
     container.RegisterPerWebRequest<IUserStore<User>>(() => new UserStore<User>(container.GetInstance<IdentityDbContext<User>>()));
     container.RegisterPerWebRequest(() => container.IsVerifying()
         ? new OwinContext(new Dictionary<string, object>()).Authentication
         : HttpContext.Current.GetOwinContext().Authentication);
 }
Пример #26
0
        public void RegisterDependencies(Container container)
        {
            container.Register <ITaskRepository, TaskRepository>();
            container.Register <NewLeadService, NewLeadService>();

            container.Verify();
        }
Пример #27
0
        protected CollectionResolver(Container container, Type serviceType)
        {
            Requires.IsNotPartiallyClosed(serviceType, nameof(serviceType));

            this.Container = container;
            this.ServiceType = serviceType;
        }
Пример #28
0
 protected virtual void Setup()
 {
     _container = new Container();
     _container.Options.AllowOverridingRegistrations = true;
     foreach (var registrar in GetRegistrars().OrderBy(x => x.Order))
         registrar.Register(_container);
 }
Пример #29
0
        public override void Configure(Container container)
        {
            container.Register<IConsole, SystemConsole>();
            container.Register<IThreadService, ThreadService>();

            ViewEngines.Add<RazorViewEngine>();
        }
        /// <summary>
        /// Constructor.  Creates a new TypeRegistrationProvider instance.
        /// </summary>
        /// <param name="container">SimpleInjector Container instance</param>
        /// <param name="options">Registration options to use to auto-register types.</param>
        public TypeRegistrationProvider(Container container, IAutoRegistrationOptions options)
        {
            this.container = container;
            this.options = options;

            this.container.Options.AllowOverridingRegistrations = true;
        }
Пример #31
0
        public static void RegistrationContainers()
        {
            var container = new Container();
            container.Options.DefaultScopedLifestyle = new WebRequestLifestyle();
            container.Register<IUnitOfWork, UnitOfWork>(Lifestyle.Scoped);
            container.Register<IAddressManager, AddressManager>();
            container.Register<ICarManager, CarManager>();
            container.Register<ICoordinatesManager, CoordinatesManager>();
            container.Register<IDistrictManager, DistrictManager>();
            container.Register<ILocationManager, LocationManager>();
            container.Register<IPersonManager, PersonManager>();
            container.Register<ITarifManager, TarifManager>();
            container.Register<IUserManager, UserManager>();
            container.Register<IDriverLocationHelper, DriverLocationHelper>();
            container.Register<IWorkerStatusManager, WorkerStatusManager>();
            container.Register<ISupportManager, SupportManager>();
            container.Register<IOrderManagerEx, OrderManagerEx>();
            container.Register<IDriverExManager, DriverExManager>();
            container.Register<ITariffExManager, TariffExManager>();
            container.Register<IFeedbackManager, FeedbackManager>();
            container.Register<INewsManager, NewsManager>();
            container.Verify();

            DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
        }
Пример #32
0
        public static Container Configuration(Container kernel)
        {
            kernel.Register<ICommercialRepository, CommercialRepository>(Lifestyle.Singleton);
            kernel.Verify();

            return kernel;
        }
Пример #33
0
        //Register Container for classes that use dependecy Injection
        private Container ConfigureSimpleInjector(IAppBuilder app)
        {
            var container = new Container();

            container.Options.DefaultScopedLifestyle = new ExecutionContextScopeLifestyle();

            container.Register<IUserStore<User, int>, UserStore>(Lifestyle.Scoped);

            container.Register<IDatabaseFactory, DatabaseFactory>(Lifestyle.Scoped);

            container.Register<IUnitOfWork, UnitOfWork>();

            container.Register<IAuthRepository, AuthRepository>();
            container.Register<ICommentRepository, CommentRepository>();
            container.Register<IUserRepository, UserRepository>();
            container.Register<ICompanyProfileRepository, CompanyProfileRepository>();
            container.Register<IInsuranceAgentProfileRepository, InsuranceAgentProfileRepository>();
            container.Register<ILeadProductRepository, LeadProductRepository>();
            container.Register<ILeadTransactionRepository, LeadTransactionRepository>();
            container.Register<IReviewPostRepository, ReviewPostRepository>();

            app.Use(async (context, next) => {
                    using (container.BeginExecutionContextScope())
                    {
                        await next();
                    }
                });

            container.Verify();

            return container;
        }
Пример #34
0
        private static void RunApp(Container container)
        {
            try
            {
                XamlGeneratedNamespace.GeneratedApplication app = new XamlGeneratedNamespace.GeneratedApplication();
                ((WpfApplication)container.GetInstance<IApplication>()).Initialize();
                app.InitializeComponent();
                app.Startup += (sender, args) =>
                {
                    ThemeManager.AddAccent("WhiteAccent",
                        new Uri("pack://application:,,,/DSImager.Application;component/Themes/WhiteAccent.xaml"));
                    ThemeManager.AddAppTheme("WhiteTheme",
                        new Uri("pack://application:,,,/DSImager.Application;component/Themes/WhiteTheme.xaml"));
                };
                var mainWin = container.GetInstance<MainWindow>();
                container.GetInstance<ILogService>().Trace(LogEventCategory.Informational, "App is starting");
                app.Run(mainWin);

            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                throw;
            }
        }
        /// <summary>Initialize the container and register it as MVC3 Dependency Resolver.</summary>
        public static void Initialize()
        {
            var container = new Container();

            InitializeContainer(container);

            try
            {
                container.Verify();
            }
            catch (Exception exception)
            {
                Trace.TraceError("{0}", exception);
                throw;
            }

            GlobalConfiguration.Configuration.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container);
            GlobalConfiguration.Configuration.Services.Replace(typeof (IFilterProvider), new SimpleInjectorWebApiFilterProvider(container));

            try
            {
                new TraceListenersInitializer(container.GetInstance<IPortalSettings>(), container.GetInstance<IEmailSenderService>()).Initialize();
            }
            catch (Exception e)
            {
                Trace.TraceError("Failed to initialize trace listeners: {0}", e);
                throw;
            }
        }
Пример #36
0
        static void Main(string[] args)
        {
            // 1. Create a new Simple Injector container
            var container = new Container();

            // 2. Configure the container (register)
            container.Register<IMongoProvider, MongoProvider>(Lifestyle.Singleton);
            container.Register<IInputProvider, MongoInputProvider>();
            container.Register<IOutputProvider, MongoOutputProvider>();
            container.Register<IParseProvider,ConsoleParseProvider>();
            container.Register<IMathProvider, DefaultMathProviderProvider>();

            // 3. Optionally verify the container's configuration.
            container.Verify();

            /*
            var calc = new Calculator(
                new MongoInputProvider(new MongoProvider("localhost:\\mongo")), //<===
                new MongoOutputProvider(new MongoProvider("localhost:\\mongo")),//<=== 
                new ConsoleParseProvider(),
                new DefaultMathProviderProvider()
                );

            */
            var calc = container.GetInstance<Calculator>();
            calc.MainLoop();

            Console.ReadLine();
        }
Пример #37
0
 public TimedHostedService(SimpleInjector.Container container, Settings settings /*, ILogger logger*/)
 {
     this.container = container;
     this.settings  = settings;
     //this.logger = logger;
     this.timer = new Timer(callback: _ => this.DoWork());
 }
Пример #38
0
 private static void RegisterFallback <TService>(this Container container, Action <UnregisteredTypeEventArgs> register) =>
 container.ResolveUnregisteredType += (_, args) =>
 {
     if (!args.Handled && args.UnregisteredServiceType == typeof(TService))
     {
         register(args);
     }
 };
Пример #39
0
        public static SimpleInjector.Container Initialize()
        {
            _container = new SimpleInjector.Container();

            _container.Options.DefaultScopedLifestyle = new WebRequestLifestyle();
            Register();
            return(_container);
        }
Пример #40
0
        public Container(SimpleInjector.Container container, bool child = false)
        {
            _container = container;
            _child     = child;

            // No support for child containers, but the scoped lifestyle can kind of due to trick
            AsyncScopedLifestyle.BeginScope(_container);
        }
        //public bool IsWebApp { get; }

        public SimpleServiceContainer()
        {
            Container = new Container();
            Container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();

            // Set to false. This will be the default in v5.x and going forward.
            Container.Options.ResolveUnregisteredConcreteTypes = false;
        }
Пример #42
0
        public static Container RegisterComponents()
        {
            var container = new SimpleInjector.Container();

            RegisterViewModels(container);
            RegisterUseCases(container);
            return(container);
        }
Пример #43
0
        private void ConfigureMvc(SimpleInjector.Container container)
        {
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            System.Web.Mvc.DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
        }
Пример #44
0
        public static void RegisterPlugins <TImplements, TExport>(this Container container,
                                                                  IEnumerable <Assembly> assemblies, Lifestyle lifestyle = null) where TExport : class
        {
            var pluginTypes = GetTypes <TImplements>(assemblies).ToArray();

            HandleLifestyle <TExport>(container, lifestyle, pluginTypes);
            container.RegisterAll <TExport>(pluginTypes);
        }
Пример #45
0
        private static void InitializeContainer(Container container)
        {
            BootStrapperApplication.RegisterServices(container);
            BootStrapperDomain.RegisterServices(container);
            BootStrapperInfra.RegisterServices(container);

            container.Register <IUserStore <ApplicationUser> >();
        }
        public static void RegisterPlugins <T>(this Container container, IEnumerable <Assembly> assemblies,
                                               Lifestyle lifestyle = null) where T : class
        {
            var pluginTypes = GetTypes <T>(assemblies).ToArray();

            HandleLifestyle <T>(container, lifestyle, pluginTypes);
            container.RegisterCollection <T>(pluginTypes);
        }
        public void Initialize()
        {
            messageContainer = new SimpleInjector.Container();

            messageContainer.Register <NLog.ILogger, LoggingCommand>(Lifestyle.Singleton);
            messageContainer.Register <IMessageProcessor <UasHeartbeat>, HeartbeatProcessor>(Lifestyle.Singleton);
            messageContainer.Register <IMessageProcessor <UasBatteryStatus>, BatteryStatusProcessor>(Lifestyle.Singleton);
            messageContainer.Register <IMessageProcessor <UasStatustext>, StatustextProcessor>(Lifestyle.Singleton);
        }
Пример #48
0
 public ValidatedBreezeContext(
     ISession session,
     IBreezeConfig breezeConfig,
     IBreezeConfigurator breezeConfigurator,
     IEventPublisher eventPublisher,
     Container container) : base(breezeConfig, session, breezeConfigurator, eventPublisher)
 {
     _container = container;
 }
Пример #49
0
        public static Configure SimpleInjector(this Configure config, SimpleInjector.Container container)
        {
            container.Options.DefaultScopedLifestyle       = new AsyncScopedLifestyle();
            container.Options.AllowOverridingRegistrations = true;

            config.Container = new Internal.Container(container);

            return(config);
        }
Пример #50
0
        public Container(SimpleInjector.Container container, bool child = false)
        {
            _container        = container;
            _child            = child;
            _namedCollections = new Dictionary <Type, List <SimpleInjector.Registration> >();

            // No support for child containers, but the scoped lifestyle can kind of due to trick
            AsyncScopedLifestyle.BeginScope(_container);
        }
Пример #51
0
 private static Container GetRegisteredContainer()
 {
     SimpleInjector.Container container = new SimpleInjector.Container();
     container.Register <IDependencyOne, DependencyOne>();
     container.Register <IDependencyTwo, DependencyTwo>();
     container.Register <IDependencyThree, DependencyThree>();
     container.Register <IProcessorFactory, ProcessorFactory>();
     return(container);
 }
Пример #52
0
        public SimpleInjectorJobActivator(Injector.Container container)
        {
            if (container == null)
            {
                throw new ArgumentNullException("container");
            }

            _container = container;
        }
Пример #53
0
        public void PerformTest()
        {
            var spCont = new SimpleInjector.Container();

            spCont.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();
            spCont.Register <ICentralConfigProvider, TestConfigProvider>(Lifestyle.Scoped);
            using (AsyncScopedLifestyle.BeginScope(spCont))
            {
                spCont.GetInstance <ICentralConfigProvider>();
            }

            var autofacBd = new Autofac.ContainerBuilder();

            autofacBd.RegisterType <TestConfigProvider>().As <ICentralConfigProvider>();
            var autofac = autofacBd.Build();

            using (var scope = autofac.BeginLifetimeScope())
            {
                autofac.Resolve <ICentralConfigProvider>();
            }


            var count = 1000;

            Console.WriteLine($"Start test {count} times: -----------------------");

            //----SimpleInjector
            var task = Task.Run(() => TestUtil.RunWatch("SimpleInjector", count, () =>
            {
                using (AsyncScopedLifestyle.BeginScope(spCont))
                {
                    var siIns = spCont.GetInstance <ICentralConfigProvider>();
                }
            }));

            //-------------------------------------------------
            var task1 = Task.Run(() => TestUtil.RunWatch("Autofac", count, () =>
            {
                using (var scope = autofac.BeginLifetimeScope())
                {
                    autofac.Resolve <ICentralConfigProvider>();
                }
            }));

            //----SimpleInjector

            /*var task = Task.Run(() => TestUtil.RunWatch("Castle", count, () =>
             * {
             *  using (castle.BeginScope())
             *  {
             *      castle.Resolve<ICentralConfigProvider>();
             *  }
             * }));*/

            task.Wait();
            task1.Wait();
        }
        private static void CriarContainerInjecaoDependencia()
        {
            container = new SimpleInjector.Container();

            container.Register <IClienteRepositorio <Cliente>, ClienteRepositorio>(Lifestyle.Singleton);
            container.Register <IContaCorrenteRepositorio <ContaCorrente>, ContaCorrenteRepositorio>(Lifestyle.Singleton);
            container.Register <IContaEspecialRepositorio <ContaEspecial>, ContaEspecialRepositorio>(Lifestyle.Singleton);
            container.Register <Form1>();
        }
Пример #55
0
        // Configure your AppHost with the necessary configuration and dependencies your App needs
        public override void Configure(Funq.Container container)
        {
            base.SetConfig(new HostConfig
            {
                DebugMode          = AppSettings.Get(nameof(HostConfig.DebugMode), false),
                HandlerFactoryPath = "api"
            });

            // plugins
            Plugins.Add(new TemplatePagesFeature());
            Plugins.Add(new ValidationFeature());

            SimpleContainer = new Container();
            //SimpleContainer.Options.DefaultScopedLifestyle = ScopedLifestyle.Flowing;

            container.Adapter = new SimpleInjectorIocAdapter(SimpleContainer);

            InitializeCache();

            InitializeDbConnectionFactory();

            InitializeMessaging();
            SimpleContainer.Register(() => Container.Adapter.Resolve <IMessageService>().MessageFactory);
            SimpleContainer.Register <IMessageProducer>(() => Container.Adapter.Resolve <IMessageFactory>().CreateMessageProducer(), Lifestyle.Transient);
            SimpleContainer.Register <IMessageQueueClient>(() => Container.Adapter.Resolve <IMessageFactory>().CreateMessageQueueClient(), Lifestyle.Transient);


            InitializeIntegrations();

            // repositories
            SimpleContainer.Register <ILinkRepository, LinkRepository>();
            SimpleContainer.Register <ITagRepository, TagRepository>();

            // validators
            SimpleContainer.Register <ITagValidator, TagValidator>();
            SimpleContainer.Collection.Register(typeof(IValidator <>), this.ServiceAssemblies);
            SimpleContainer.Collection.Register(typeof(ICreateLinkScreenshotHandler), this.ServiceAssemblies);

            //SimpleContainer.RegisterDecorator(...); // https://cuttingedge.it/blogs/steven/pivot/entry.php?id=93

            // events
            SimpleContainer.RegisterInstance <IEventBus>(new DomainEventBus(SimpleContainer));
            SimpleContainer.Collection.Register(typeof(IEventHandler <>), this.ServiceAssemblies);

            // Done container registration!
            SimpleContainer.Verify(VerificationOption.VerifyOnly);

            OnConfigEnding();

            // Messaging Service
            var mqHost = Container.Adapter.Resolve <IMessageService>();

            mqHost.RegisterHandler <CreateLinkScreenshotRequest>(base.ExecuteMessage);

            mqHost.Start();
        }
Пример #56
0
        private static void InitializeContainer(SimpleInjector.Container container)
        {
            container.Options.DefaultScopedLifestyle = new ExecutionContextScopeLifestyle();
            container.Register <ErpContext>(Lifestyle.Scoped);
            container.Register(typeof(IUnitOfWork <>), typeof(UnitOfWork <>), Lifestyle.Scoped);

            container.Register <ISorteioService, SorteioService>();
            container.Register <IJogadorService, JogadorService>();
            container.Register <IJogoService, JogoService>();
        }
Пример #57
0
 private static Container GetRegisteredContainer()
 {
     SimpleInjector.Container container = new SimpleInjector.Container();
     container.Register <IDependencyOne, DependencyOne>();
     container.Register <IDependencyTwo, DependencyTwo>();
     container.Register <IDependencyThree, DependencyThree>();
     container.Register <IProcessorFactory, ProcessorFactory>();
     container.RegisterCollection <IProcessor>(new Assembly[] { Assembly.GetExecutingAssembly() });
     return(container);
 }
Пример #58
0
        public Form1()
        {
            InitializeComponent();

            CustomerContainer = new Container();
            CustomerContainer
            .Register <ICustomer, SqlCustomerData>(Lifestyle.Singleton);

            CustomerContainer.Verify();
        }
Пример #59
-1
 public WebApiDependencyResolver(Container container)
 {
     if (container == null)
         throw new ArgumentNullException("container");
     _container = container;
     _provider = container;
 }
Пример #60
-1
        static void Main(string[] args)
        {   
            // Configure container
            var container = new Container();
            container.Register<IClock, Clock>();

            // Top shelf setup
            HostFactory.Run(
                config =>
                    {
                        config.UseSimpleInjector(container);
                        config.UseLog4Net("log4net.xml");

                        config.Service<Clock>(
                            s =>
                                {
                                    s.ConstructUsingSimpleInjector();
                                    s.WhenStarted(tc => tc.Start());
                                    s.WhenStopped(tc => tc.Stop());
                                });

                        config.SetDescription("TopShelf Demo service");
                        config.SetDisplayName("TopShelf Demo");
                        config.SetServiceName("TopShelfDemo");
                    });
        }