Exemplo n.º 1
0
 public override void Prepare()
 {
     this.container = new IocContainer();
     this.container.Register<ISingleton, Singleton>().WithLifetimeManager(new ContainerLifetime());
     this.container.Register<ITransient, Transient>().WithLifetimeManager(new AlwaysNewLifetime());
     this.container.Register<ICombined, Combined>().WithLifetimeManager(new AlwaysNewLifetime());
 }
Exemplo n.º 2
0
        static MunqUseCase()
        {
            container = new IocContainer();
            singleton = new Munq.LifetimeManagers.ContainerLifetime();

            container.Register<IWebService>(
                c => new WebService(
                    c.Resolve<IAuthenticator>(),
                    c.Resolve<IStockQuote>()));

            container.Register<IAuthenticator>(
                c => new Authenticator(
                    c.Resolve<ILogger>(),
                    c.Resolve<IErrorHandler>(),
                    c.Resolve<IDatabase>()));

            container.Register<IStockQuote>(
                c => new StockQuote(
                    c.Resolve<ILogger>(),
                    c.Resolve<IErrorHandler>(),
                    c.Resolve<IDatabase>()));

            container.Register<IDatabase>(
                c => new Database(
                    c.Resolve<ILogger>(),
                    c.Resolve<IErrorHandler>()));

            container.Register<IErrorHandler>(
                c => new ErrorHandler(c.Resolve<ILogger>()));

            container.RegisterInstance<ILogger>(new Logger())
                    .WithLifetimeManager(singleton);
        }
Exemplo n.º 3
0
		public void CanSetDefaultLifetimeToSessionLifetime()
		{
			using (var container = new IocContainer(() => new SessionLifetime()))
			{
				Assert.IsInstanceOfType(container.DefaultLifetimeFactory(), typeof(SessionLifetime));
			}
		}
Exemplo n.º 4
0
        public void TransientLifetimeAlwaysReturnsANewInstance()
        {
            // Arrange
            using (var container = new IocContainer())
            {
                container.Register<IFoo>(c => new Foo1());	//.SetLifetime(new TransientLifetime<IFoo>);

                // Act
                var result1 = container.Resolve<IFoo>();
                var result2 = container.Resolve<IFoo>();
                var result3 = container.Resolve<IFoo>();

                // Assert
                Assert.IsNotNull(result1);
                Assert.IsNotNull(result2);
                Assert.IsNotNull(result3);

                Assert.AreNotSame(result1, result2);
                Assert.AreNotSame(result2, result3);
                Assert.AreNotSame(result1, result3);

                Assert.IsInstanceOfType(result1, typeof(Foo1));
                Assert.IsInstanceOfType(result2, typeof(Foo1));
                Assert.IsInstanceOfType(result3, typeof(Foo1));
            }
        }
Exemplo n.º 5
0
        public void TryResolveAllReturnsExpectedInstances()
        {
            using (var container = new IocContainer())
            {
                // Arrange
                var foo1 = new Foo1();
                var foo2 = new Foo2();
                var foo3 = new Foo2();
                var bar1 = new Bar1();

                container.RegisterInstance<IFoo>(foo1);
                container.RegisterInstance<IFoo>(foo2, "Foo1");
                container.RegisterInstance<IFoo>(foo3, "Foo2");
                container.RegisterInstance<IBar>(bar1);

                // Act
                var results = container.TryResolveAll<IFoo>();

                var resultList = results.ToList();

                // Assert
                Assert.IsTrue(results.Count() == 3);

                CollectionAssert.Contains(resultList, foo1);
                CollectionAssert.Contains(resultList, foo2);
                CollectionAssert.Contains(resultList, foo3);
            }
        }
Exemplo n.º 6
0
		public void SessionLifetimeReturnsSameInstanceForSameSessionAndDifferentInstanceForDifferentSession()
		{
			// Arrange
			using (var container = new IocContainer())
			{
				var sessionItems1 = new SessionStateItemCollection();
				var sessionItems2 = new SessionStateItemCollection();
				var context1 = new FakeHttpContext("Http://fakeUrl1.com", null, null, null, null, sessionItems1);
				var context2 = new FakeHttpContext("Http://fakeUrl2.com", null, null, null, null, sessionItems2);

				HttpContextBase currentContext = null;

				var lifetime = new SessionLifetime(() => currentContext);		// better solution for injecting HttpContext ?

				container.Register<IFoo>(c => new Foo1()).SetLifetime(lifetime);

				// Act
				currentContext = context1;

				var result1 = container.Resolve<IFoo>();
				var result2 = container.Resolve<IFoo>();

				currentContext = context2;

				var result3 = container.Resolve<IFoo>();

				// Assert
				Assert.IsNotNull(result1);
				Assert.IsNotNull(result2);
				Assert.IsNotNull(result3);

				Assert.AreSame(result1, result2);
				Assert.AreNotSame(result1, result3);
			}
		}
Exemplo n.º 7
0
 public void DefaultLifetimeIsDefaultSetToTransient()
 {
     using (var container = new IocContainer())
     {
         Assert.IsInstanceOfType(container.DefaultLifetime, typeof(TransientLifetime));
     }
 }
Exemplo n.º 8
0
 public void GenericResolveByTypeNotRegisteredThrowsException()
 {
     using (var container = new IocContainer())
     {
         container.Resolve<IFoo>();
     }
 }
Exemplo n.º 9
0
        public void Configuration(IAppBuilder appBuilder)
        {
            IIocContainer iocContainer = new IocContainer();

            Bootstrap.Application()
                .ResolveReferencesWith(iocContainer)
                .UseEnvironment()
                .UseDomain().WithSimpleMessaging()
                .ConfigureRouteInspectorServer().WithRouteLimitOf(10)
                .ConfigureRouteInspectorWeb()
                .UseEventSourcing().PersistToMemory()
                .Initialise();

            var configuration = new HttpConfiguration
            {
                DependencyResolver = new SystemDotDependencyResolver(iocContainer)
            };

            configuration.MapHttpAttributeRoutes();
            configuration.Filters.Add(new ModelStateContextFilterAttribute());
            configuration.Filters.Add(new NoCacheFilterAttribute());

            configuration.MapSynchronisationRoutes();

             configuration.Routes.MapHttpRoute(
                  "Default",
                  "{controller}/{id}",
                  new { id = RouteParameter.Optional });
            
            appBuilder.UseWebApi(configuration);
        }
Exemplo n.º 10
0
		public void ThreadLocalStorageLifetimeReturnsSameInstanceForSameThread()
		{
			using (var container = new IocContainer())
			{
				container.Register<IFoo>(c => new Foo1()).SetLifetime(new ThreadLocalLifetime());

				IFoo result1 = container.Resolve<IFoo>();
				IFoo result2 = container.Resolve<IFoo>();

				IFoo result3 = null;
				IFoo result4 = null;

				// Resolve on a different thread
				var task = Task.Factory.StartNew(() =>
				{
					result3 = container.Resolve<IFoo>();
					result4 = container.Resolve<IFoo>();
				});

				task.Wait();

				// Assert
				Assert.IsNotNull(result1);
				Assert.IsNotNull(result2);
				Assert.IsNotNull(result3);
				Assert.IsNotNull(result4);

				Assert.AreSame(result1, result2);
				Assert.AreSame(result3, result4);

				Assert.AreNotSame(result1, result3);
			}
		}
Exemplo n.º 11
0
 public void DefaultLifetimeMangerIsNull()
 {
     using (var iocContainer = new IocContainer())
     {
         Assert.IsNull(iocContainer.DefaultLifetimeManager);
     }
 }
Exemplo n.º 12
0
		public void CanSetDefaultLifetimeToThreadLocalStorageLifetime()
		{
			using (var container = new IocContainer(() => new ThreadLocalLifetime()))
			{
				Assert.IsInstanceOfType(container.DefaultLifetimeFactory(), typeof(ThreadLocalLifetime));
			}
		}
Exemplo n.º 13
0
 public void CanSetDefaultLifetimeToTransient()
 {
     using (var container = new IocContainer(() => new TransientLifetime()))
     {
         Assert.IsInstanceOfType(container.DefaultLifetime, typeof(TransientLifetime));
     }
 }
Exemplo n.º 14
0
 public void GenericResolveByNameNotRegisteredThrowsException2()
 {
     using (var container = new IocContainer())
     {
         container.Register<IFoo>(c => new Foo1());
         container.Resolve<IFoo>("Foo");
     }
 }
Exemplo n.º 15
0
        public override void PrepareBasic()
        {
            this.container = new IocContainer();

            this.RegisterDummies();
            this.RegisterStandard();
            this.RegisterComplex();
        }
Exemplo n.º 16
0
        protected void Application_Start()
        {
            IocContainer = new IocContainer();

            AreaRegistration.RegisterAllAreas();

            RegisterRoutes(RouteTable.Routes);
        }
Exemplo n.º 17
0
 public void GetServiceTest2()
 {
     var type = typeof(DefaultService1);
     var container = new IocContainer();
     container.AddService(type, true);
     var childContainer = new IocContainer(container);
     Assert.Equal(childContainer.GetService(type), container.GetService(type));
 }
Exemplo n.º 18
0
        public void AddService_TypeObjectBoolean_Test1()
        {
            var container = new IocContainer();
            container.AddService(typeof(IService2), new XService2());

            var childContainer = new IocContainer(container);
            Assert.IsAssignableFrom<XService2>(childContainer.GetService(typeof(IService2)));
        }
Exemplo n.º 19
0
        public void CanSetProvider()
        {
            var resolver = new IocContainer();
            var locator = new DynamoServiceLocator(resolver);
            ServiceLocator.SetLocatorProvider(() => locator);

            // No way to get provider from ServiceLocator.Current to verify!!
        }
Exemplo n.º 20
0
        public void GetServiceTest1()
        {
            var itype = typeof(IService1);
            var container = new IocContainer();

            Assert.False(container.ContainsService(itype));
            Assert.NotNull(container.GetService(itype));
            Assert.False(container.ContainsService(typeof(IService_NotFound)));
            Assert.Null(container.GetService(typeof(IService_NotFound)));
        }
Exemplo n.º 21
0
		public void ResolveAllByTypeNotRegisteredThrowsException()
		{
			using (var container = new IocContainer())
			{
				var results = container.ResolveAll<IFoo>();

				// Doesnt throw exception before it is enumerated because it uses yield return - OK ?
				var test = results.Count();
			}
		}
Exemplo n.º 22
0
        public void CanSetDefaultLifetimeManagerToContainerLifetime()
        {
            using (var iocContainer = new IocContainer())
            {
                var lifetime = new ContainerLifetime();
                iocContainer.UsesDefaultLifetimeManagerOf(lifetime);

                Verify.That(iocContainer.DefaultLifetimeManager).IsTheSameObjectAs(lifetime);
            }
        }
Exemplo n.º 23
0
        void SettingTheDefaultContainerLifetime()
        {
            // create the container.  Only done once in Application_Start
            IocContainer iocContainer = new IocContainer();

            // create a lifetime manager to use as default
            ILifetimeManager lifetimeManager = new LifetimeManagers.RequestLifetime();

            // set the default lifetime manager
            iocContainer.UsesDefaultLifetimeManagerOf(lifetimeManager);
        }
Exemplo n.º 24
0
        static MunqGenericUseCase()
        {
            container = new IocContainer();

            //container.Register<IWebService, WebService>();
            container.Register<IAuthenticator, Authenticator>();
            container.Register<IStockQuote, StockQuote>();
            container.Register<IDatabase, Database>();
            container.Register<IErrorHandler, ErrorHandler>();
            container.Register<ILogger,Logger>().WithLifetimeManager(singleton);
        }
Exemplo n.º 25
0
        /// <summary>
        ///   Initialize method called from XDMessaging.Core before the instance is constructed.
        ///   This allows external classes to registered dependencies with the IocContainer.
        /// </summary>
        /// <param name = "container">The IocContainer instance used to construct this class.</param>
        private static void Initialize(IocContainer container)
        {
            Validate.That(container).IsNotNull();

            container.Register(AmazonAccountSettings.GetInstance, LifeTime.Singleton);
            container.Register<ITopicRepository, TopicRepository>(LifeTime.Singleton);
            container.Register<ISubscriberRepository, SubscriberRepository>(LifeTime.Singleton);
            container.Register<IQueuePoller, QueuePoller>(LifeTime.Singleton);
            container.Register<IAmazonSqsFacade, AmazonSqsFacade>(LifeTime.Singleton);
            container.Register<IAmazonSnsFacade, AmazonSnsFacade>(LifeTime.Singleton);
        }
Exemplo n.º 26
0
        public void GenericResolveByTypeReturnsInstanceOfExpectedType()
        {
            using (var container = new IocContainer())
            {
                container.Register<IFoo>(c => new Foo1());
                var result = container.Resolve<IFoo>();

                Assert.IsNotNull(result);
                Assert.IsInstanceOfType(result, typeof(IFoo));
                Assert.IsInstanceOfType(result, typeof(Foo1));
            }
        }
Exemplo n.º 27
0
        public void TestRegisterSingletonClass()
        {
            var container = new IocContainer();
            container.Register(typeof(ConnectionName), LifestyleType.Singleton);

            ConnectionName connectionName = (ConnectionName)container.Resolve(typeof(ConnectionName));
            Assert.NotNull(connectionName);

            ConnectionName connectionName2 = (ConnectionName)container.Resolve(typeof(ConnectionName));
            Assert.NotNull(connectionName);
            Assert.Equal(connectionName, connectionName2);
        }
Exemplo n.º 28
0
        public void RunBeforeAnyTests()
        {
            //NHibernateProfiler.Initialize();
            Container = new IocContainer();

            Fac.Default.Interceptors.Add(t => new HardenInterceptor());
            {
                Fac.Default.SetServiceLocator(Container.Resolve, Container.CanResolve);
            }

            NHibernateConfigurator.Configure(Container, new ThreadLocalStorageLifetime());
        }
Exemplo n.º 29
0
        public void TestRegisterSingletonClassGeneric()
        {
            var container = new IocContainer();
            container.Register<ConnectionName>(LifestyleType.Singleton);

            ConnectionName connectionName = container.Resolve<ConnectionName>();
            Assert.NotNull(connectionName);

            ConnectionName connectionName2 = container.Resolve<ConnectionName>();
            Assert.NotNull(connectionName);
            Assert.Equal(connectionName, connectionName2);
        }
Exemplo n.º 30
0
		public void TryResolveByTypeNotRegisteredReturnsFalseAndNull()
		{
			using (var container = new IocContainer())
			{
				// Act
				IFoo obj;
				bool result = container.TryResolve<IFoo>(out obj);

				// Assert
				Assert.IsFalse(result);
				Assert.IsNull(obj);
			}
		}
Exemplo n.º 31
0
        public void CanResolve()
        {
            IocContainer.Resolve <ISingleZipCodeProcessor>().Should().NotBeNull();
            IocContainer.Resolve <IPersistenceInitializer>().Should().NotBeNull();
            IocContainer.Resolve <IZipCodeUrlSerializer>().Should().NotBeNull();
            IocContainer.Resolve <IStoreInfoResponseDataService>().Should().NotBeNull();
            IocContainer.Resolve <IZipCodeDataService>().Should().NotBeNull();
            IocContainer.Resolve <IAllZipCodesProcessor>().Should().NotBeNull();
            IocContainer.Resolve <IDelaySimulator>().Should().NotBeNull();
            IocContainer.Resolve <ICacheWithExpiration>().Should().NotBeNull();
            IocContainer.Resolve <IStorePersistenceCalculator>().Should().NotBeNull();
            IocContainer.Resolve <ITimerFactory>().Should().NotBeNull();

            ValidateSingletonRegistration <IMemoryCache>();
        }
        public virtual void Start()
        {
            Initialize();
            if (!MvvmApplication.Context.Contains(NavigationConstants.IsDialog))
            {
                MvvmApplication.Context.Add(NavigationConstants.IsDialog, false);
            }
            var rootPresenter = GetRootPresenter();

            if (rootPresenter != null)
            {
                IocContainer.Get <IViewModelPresenter>().DynamicPresenters.Add(rootPresenter);
            }
            MvvmApplication.Start();
        }
Exemplo n.º 33
0
        public void TestCycleInClassesBoundByInterfaceTakingInterfaceTypes()
        {
            var ioc = new IocContainer();

            ioc.Bind <ICyclicA, CyclicAThroughInterface>();
            ioc.Bind <ICyclicB, CyclicBThroughInterface>();

            Assert.ThrowsException <ActivationException>(
                () => ioc.Resolve <ICyclicA>()
                );

            Assert.ThrowsException <ActivationException>(
                () => ioc.Resolve <ICyclicB>()
                );
        }
Exemplo n.º 34
0
        public void TestRegisterTransientClassGeneric()
        {
            var container = new IocContainer();

            container.Register <ConnectionName>();

            ConnectionName connectionName = container.Resolve <ConnectionName>();

            Assert.NotNull(connectionName);

            ConnectionName connectionName2 = container.Resolve <ConnectionName>();

            Assert.NotNull(connectionName);
            Assert.NotEqual(connectionName, connectionName2);
        }
Exemplo n.º 35
0
        protected override bool LoadInternal()
        {
#if DEBUG
            IocContainer.Bind <ICurrentWeatherDataProvider, FakeCurrentWeatherDataProvider>(DependencyLifecycle.SingleInstance);
            //IocContainer.Bind<ICurrentWeatherDataProvider, NarodMonWeatherDataProvider>(DependencyLifecycle.SingleInstance);

            IocContainer.Bind <IWeatherForecastDataProvider, FakeWeatherForecastDataProvider>(DependencyLifecycle.SingleInstance);
            //IocContainer.Bind<IWeatherForecastDataProvider, Rp5WeatherForecastDataProvider>(DependencyLifecycle.SingleInstance);
#else
            IocContainer.Bind <ICurrentWeatherDataProvider, NarodMonWeatherDataProvider>(DependencyLifecycle.SingleInstance);
            IocContainer.Bind <IWeatherForecastDataProvider, Rp5WeatherForecastDataProvider>(DependencyLifecycle.SingleInstance);
#endif

            return(true);
        }
Exemplo n.º 36
0
        public void TestRegisterSingletonClass()
        {
            var container = new IocContainer();

            container.Register(typeof(ConnectionName), LifestyleType.Singleton);

            ConnectionName connectionName = (ConnectionName)container.Resolve(typeof(ConnectionName));

            Assert.NotNull(connectionName);

            ConnectionName connectionName2 = (ConnectionName)container.Resolve(typeof(ConnectionName));

            Assert.NotNull(connectionName);
            Assert.Equal(connectionName, connectionName2);
        }
Exemplo n.º 37
0
        private static void RegisterPropertyProviders(IServiceCollection services)
        {
            var iocContainer = new IocContainer(services);

            ImmoscoutProviderBootstrapper.Register(iocContainer);
            ImmoscoutListProviderBootstrapper.Register(iocContainer);
            ImmoXXLProviderBootstrapper.Register(iocContainer);
            ImmosuchmaschineProviderBoostrapper.Register(iocContainer);
            KskProviderBootstrapper.Register(iocContainer);
            OhneMaklerProviderBoostrapper.Register(iocContainer);
            VolksbankFlowfactProviderBootstrapper.Register(iocContainer);
            VolksbankImmopoolProviderBootstrapper.Register(iocContainer);
            WunschimmoProviderBootstrapper.Register(iocContainer);
            ZvgProviderBootstrapper.Register(iocContainer);
        }
Exemplo n.º 38
0
        public void AddService_TypeBooleanBoolean_Test1()
        {
            var type  = typeof(DefaultService1);
            var itype = typeof(IService1);

            var container = new IocContainer();

            container.AddService(type);

            Assert.NotNull(container.GetService(type));
            Assert.NotNull(container.GetService(itype));
            Assert.NotEqual(container.GetService(type), container.GetService(type));
            Assert.NotEqual(container.GetService(type), container.GetService(itype));
            Assert.IsAssignableFrom(type, container.GetService(itype));
        }
Exemplo n.º 39
0
        protected virtual IDynamicViewModelPresenter GetRootPresenter()
        {
            if (RootPresenterFactory != null)
            {
                return(RootPresenterFactory(IocContainer));
            }
            if (WrapToNavigationController)
            {
                return(null);
            }
            var presenter = IocContainer.Get <TouchRootDynamicViewModelPresenter>();

            presenter.Window = Window;
            return(presenter);
        }
Exemplo n.º 40
0
        public void CanCreateSimpleTypeWithOneParameterUsingFactoryMethod()
        {
            var container = new IocContainer();

            container.Register(() => new MySimpleThing()
            {
                MyName = "MyNameIsBob"
            });
            container.Register <MySlightlySimpleThing>();
            var mySlightlySimpleThing = container.Resolve <MySlightlySimpleThing>();

            mySlightlySimpleThing.Should().NotBeNull();
            mySlightlySimpleThing.SimpleThing.Should().NotBeNull();
            mySlightlySimpleThing.SimpleThing.MyName.Should().Be("MyNameIsBob");
        }
Exemplo n.º 41
0
        public void TestRegisterSingletonClassGeneric()
        {
            var container = new IocContainer();

            container.Register <ConnectionName>(LifestyleType.Singleton);

            ConnectionName connectionName = container.Resolve <ConnectionName>();

            Assert.NotNull(connectionName);

            ConnectionName connectionName2 = container.Resolve <ConnectionName>();

            Assert.NotNull(connectionName);
            Assert.Equal(connectionName, connectionName2);
        }
        public void NamedTypeWithParametersRegistrationResolvesToCorrectType()
        {
            using (var container = new IocContainer())
            {
                container.Register <IFoo, Foo1>();
                container.Register <IBar, Bar1>();
                container.Register <IFooBar, FooBar>("bob");

                IFooBar result = container.Resolve <IFooBar>("bob");

                Verify.That(result).IsNotNull().IsAnInstanceOfType(typeof(FooBar));
                Verify.That(result.foo).IsNotNull().IsAnInstanceOfType(typeof(Foo1));
                Verify.That(result.bar).IsNotNull().IsAnInstanceOfType(typeof(Bar1));
            }
        }
Exemplo n.º 43
0
        private async void OnRequestHomePage(HomeViewModel hVm)
        {
            //Did Load will assign through Actions to Post view models, we need to assign this action early, but it is safe due to shared services
            hVm.RequestCommentPage = OnRequestCommentPage;

            if (_viewModel == null && IocContainer.GetContainer().Resolve <ITwitterApi>().GetType() == typeof(MockTwitterApi))
            {
                await Task.Delay(5000);
            }

            await hVm.DidLoad();

            //TODO add back in the grow animation
            _navigationService.NavigateTo(ViewModelLocator.HOME_KEY, hVm, null, Shared.Common.AnimationFlag.Grow);
        }
Exemplo n.º 44
0
        public void TestRegisterTransientClass()
        {
            var container = new IocContainer();

            container.Register(typeof(ConnectionName));

            ConnectionName connectionName = (ConnectionName)container.Resolve(typeof(ConnectionName));

            Assert.NotNull(connectionName);

            ConnectionName connectionName2 = (ConnectionName)container.Resolve(typeof(ConnectionName));

            Assert.NotNull(connectionName);
            Assert.NotEqual(connectionName, connectionName2);
        }
Exemplo n.º 45
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            IocContainer.Setup();
            //AreaRegistration.RegisterAllAreas();

            //RegisterGlobalFilters(GlobalFilters.Filters);
            //RegisterRoutes(RouteTable.Routes);

            //// Add this line to Application_Start in Global.asax.cs to setup the IoC Container.
            //IocContainer.Setup();
        }
Exemplo n.º 46
0
        public void TestGetAllInstances()
        {
            var ioc = new IocContainer();

            var inst1 = new Concrete();
            var inst2 = new Concrete();

            ioc.Bind <ITest>(() => inst1);
            ioc.Bind <ITest>("key", () => inst2);

            IServiceLocator locator = ioc;

            object[] instances = locator.GetAllInstances(typeof(ITest)).ToArray();
            CollectionAssert.AreEqual(new[] { inst1, inst2 }, instances);
        }
Exemplo n.º 47
0
        void SettingTheLifetimeManagerForARegistration()
        {
            // create the container.  Only done once in Application_Start
            IocContainer iocContainer = new IocContainer();

            // create a Container lifetime manager to use for 'singelton' services
            // only one instance will be created and reused for each resolve request.
            ILifetimeManager containerLifetimeManager = new LifetimeManagers.ContainerLifetime();

            iocContainer.Register <IMembershipService>(ioc => new AccountMembershipService(Membership.Provider))
            .WithLifetimeManager(containerLifetimeManager);

            iocContainer.Register <IFormsAuthenticationService>(ioc => new FormsAuthenticationService())
            .WithLifetimeManager(containerLifetimeManager);
        }
Exemplo n.º 48
0
        public ICommandExecutorContainer RegisterExecutor <TExecutor>()
            where TExecutor : class, ICommandExecutor
        {
            var executor       = IocContainer.Resolve <TExecutor>();
            var executorConfig = new CommandExecutorConfig(executor);

            CheckExecutorConfigDuplicate(executorConfig);
            _executorConfigs.Add(executorConfig);
            if (_dbContext == null)
            {
                _dbContext = executor.DbContext;
            }

            return(this);
        }
        public void RegisterInstanceGenericReturnsCorrectType()
        {
            using (var container = new IocContainer())
            {
                var fooInstance = new Foo1();
                var reg         = container.RegisterInstance <IFoo>(fooInstance);

                Assert.IsInstanceOfType(reg, typeof(InstanceRegistration <IFoo>));

                Assert.AreSame(reg.ReturnType, typeof(IFoo));

                // Check index
                Assert.IsTrue(container.Index.Contains(typeof(IFoo)));
            }
        }
        public void RegisterInstanceUsingKeyReturnsCorrectType()
        {
            using (var container = new IocContainer())
            {
                var fooInstance = new Foo1();
                var result      = container.RegisterInstance(typeof(IFoo), fooInstance, "Bar");

                Assert.IsInstanceOfType(result, typeof(InstanceRegistration <IFoo>));

                Assert.AreSame(result.ReturnType, typeof(IFoo));

                // Check index
                Assert.IsTrue(container.Index.Contains(typeof(IFoo), "Bar"));
            }
        }
        public void NonGenericNamelessLazyResolveReturnsDelegateReturningObjectOfExpectedType()
        {
            using (var iocContainer = new IocContainer())
            {
                iocContainer.Register(typeof(IFoo), c => new Foo1());
                var result = iocContainer.LazyResolve(typeof(IFoo));

                Verify.That(result)
                .IsNotNull()
                .IsAnInstanceOfType(typeof(Func <object>));

                Verify.That(result())
                .IsAnInstanceOfType(typeof(Foo1));
            }
        }
        public void GetRegistrationsReturnsAnEmptyListIfNoRegistrationsOfTheRequesetedType()
        {
            using (var iocContainer = new IocContainer())
            {
                iocContainer.Register <IFoo>(c => new Foo1());
                iocContainer.Register <IFoo>("Bob", c => new Foo2());
                iocContainer.Register <IFoo>("Bill", c => new Foo2());

                var result = iocContainer.GetRegistrations <IBar>();

                Verify.That(result.ToList()).IsACollectionThat()
                .IsAnInstanceOfType(typeof(List <IRegistration>))
                .Count().IsEqualTo(0);
            }
        }
        public void UsesDefaultLifetimeManagerOfChangesTheDefaultLifetimeManager()
        {
            using (var iocContainer = new IocContainer())
            {
                var aLifetimeManager = new LifetimeManagers.ContainerLifetime();
                iocContainer.UsesDefaultLifetimeManagerOf(aLifetimeManager);

                iocContainer.Register <IFoo>(c => new Foo1());
                var foo1 = iocContainer.Resolve <IFoo>();
                var foo2 = iocContainer.Resolve <IFoo>();

                Verify.That(iocContainer.DefaultLifetimeManager).IsTheSameObjectAs(aLifetimeManager);
                Verify.That(foo1).IsTheSameObjectAs(foo2);
            }
        }
Exemplo n.º 54
0
        public override IWindow Initialize(EventArgs e = null)
        {
            // MainWindow event subscriptions
            MainWindow.configEdit.TextArea.TextEntered  += TextArea_TextEntered;
            MainWindow.configEdit.TextArea.TextEntering += TextArea_TextEntering;

            MainWindow.queryEdit.TextArea.TextEntered  += TextArea_TextEntered;
            MainWindow.queryEdit.TextArea.TextEntering += TextArea_TextEntering;

            MainWindow.grdMainData.AutoGeneratingColumn += DataGrid_AutoGeneratingColumn;
            MainWindow.KeyDown += MainWindow_KeyDown;

            // When the view is loaded we'll invoke the ReadCsvCommand in case the user
            // double clicked a file, the null lets command now we were not a button click
            MainWindow.Loaded += (s, para) =>
            {
                InvokeCommand(ReadCsvCommand.CommandName, null);

                // Bind F5-F6 key to execute commands
                var queryCommand      = IocContainer.Resolve <ICommand>(QueryCommand.CommandName);
                var resetQueryCommand = IocContainer.Resolve <ICommand>(ResetQueryCommand.CommandName);

                var f5 = new InputBinding(queryCommand, new KeyGesture(Key.F5)); MainWindow.InputBindings.Add(f5);
                var f6 = new InputBinding(resetQueryCommand, new KeyGesture(Key.F6)); MainWindow.InputBindings.Add(f6);
            };

            MainWindow.Closed += MainWindow_Closed;

            MainViewModel.ErrorMessages.CollectionChanged += (_, __) =>
                                                             MainViewModel.HasErrorMessages = MainViewModel.ErrorMessages.Count > 0;

            MainViewModel.Host = IocContainer.Resolve <CsvEditSharpConfigurationHost>();
            IocContainer.RegisterInstance <ICsvEditSharpConfigurationHost>(MainViewModel.Host);
            IocContainer.RegisterInstance <IList <string> >(MainViewModel.ErrorMessages);

            MainViewModel.Workspace = IocContainer.Resolve <CsvEditSharpWorkspace>();

            MainViewModel.ConfigurationDoc = new TextDocument(StringTextSource.Empty);
            MainViewModel.QueryDoc         = new TextDocument(new StringTextSource("Query<FieldData>( records => records.Where(row => true));"));

            MainViewModel.CurrentFilePath   = string.Empty;
            MainViewModel.CurrentFileName   = "(Empty)";
            MainViewModel.CurrentConfigName = "(Empty)";
            MainViewModel.SelectedTemplate  = MainViewModel.ConfigFileTemplates.First();
            MainViewModel.SelectedTab       = 0;

            return(MainWindow);
        }
Exemplo n.º 55
0
        public DataResult <Transfer> CreateTransferSINSIN(int character, [FromBody] CreateTransferSinSinRequest request)
        {
            var manager = IocContainer.Get <IBillingManager>();
            DataResult <Transfer> result;

            if (string.IsNullOrEmpty(request.SinTo))
            {
                result = RunAction(() => manager.MakeTransferSINSIN(character, request.CharacterTo, request.Amount, request.Comment), "transfer/createtransfersinsin");
            }
            else
            {
                result = RunAction(() => manager.MakeTransferSINSIN(character, request.SinTo, request.Amount, request.Comment), $"transfer/createtransfersinsin {character}=>{request.SinTo}:{request.Amount}");
            }

            return(result);
        }
Exemplo n.º 56
0
        public void IsTurnCompleteGermainYes()
        {
            IocContainer.Setup();

            UnitList units = new UnitList(new BattleCalculator(new DieRoller()), new TerrainMap(new ShortestPath()));

            units.Add(2, 2, 0, NATIONALITY.Germany);
            units.Add(3, 3, 0, NATIONALITY.USA);
            units.Add(4, 4, 0, NATIONALITY.Germany);
            units[0].Movement = 0;
            units[0].UnitHasAttackedThisTurn = true;
            units[2].Movement = 0;
            units[2].UnitHasAttackedThisTurn = true;

            Assert.True(units.IsTurnComplete(NATIONALITY.Germany));
        }
Exemplo n.º 57
0
        public void Resolve_VeryComplexNotSameInstanceFromContainer2()
        {
            // test of resolving a type that has dependent parameter types
            // to see if the instance is transient
            IMyContainer container = new IocContainer();

            container.Register <System.Xml.XmlDocument, System.Xml.XmlDocument>(LifeCycle.Singleton);
            container.Register <StringBuilder, StringBuilder>(LifeCycle.Singleton);
            container.Register <VeryComplexType, VeryComplexType>();

            VeryComplexType expected = container.Resolve <VeryComplexType>();

            VeryComplexType actual = container.Resolve <VeryComplexType>();

            Assert.NotSame(expected, actual);
        }
Exemplo n.º 58
0
        public void RemoveServiceTest2()
        {
            var container      = new IocContainer();
            var childContainer = new IocContainer(container);
            var itype          = typeof(IService2);

            childContainer.Add(itype, lmp => new XService2(), promote: true);
            Assert.True(container.Contains(itype));
            Assert.True(childContainer.Contains(itype));
            container.Add(itype, lmp => new DefaultService2());
            Assert.IsAssignableFrom <XService2>(childContainer.Get(itype));
            Assert.IsAssignableFrom <DefaultService2>(container.Get(itype));
            childContainer.Remove(itype, true);
            Assert.False(container.Contains(itype));
            Assert.False(childContainer.Contains(itype));
        }
Exemplo n.º 59
0
        public async void should_resolve_from_thread_static()
        {
            var container = new IocContainer();

            container.Register <IDummyType>(iocContainer =>
            {
                return(ThreadIndependentResolver <IDummyType> .instance ?? (ThreadIndependentResolver <IDummyType> .instance = new DummyType()));
            });
            var instance         = container.Resolve <IDummyType>();
            var threadedInstance = await Task.Run(() =>
            {
                return(container.Resolve <IDummyType>());
            });

            Assert.NotEqual(instance, threadedInstance);
        }
Exemplo n.º 60
0
        public void TestConfigure()
        {
            var ioc = new IocContainer();

            ioc.Configure(new TestOptions
            {
                IntValue    = 5,
                StringValue = "TEST",
            });

            var svc = ioc.Resolve <TestService>();

            Assert.IsNotNull(svc.Configuration.Value);
            Assert.AreEqual(5, svc.Configuration.Value.IntValue);
            Assert.AreEqual("TEST", svc.Configuration.Value.StringValue);
        }