public void SimpleUsage()
		{
			IKernel kernel = new DefaultKernel();
			kernel.AddComponent("a", typeof(PoolableComponent1));

			PoolableComponent1 inst1 = kernel["a"] as PoolableComponent1;
			PoolableComponent1 inst2 = kernel["a"] as PoolableComponent1;

			Assert.IsNotNull(inst1);
			Assert.IsNotNull(inst2);

			kernel.ReleaseComponent(inst2);
			kernel.ReleaseComponent(inst1);

			PoolableComponent1 other1 = kernel["a"] as PoolableComponent1;
			PoolableComponent1 other2 = kernel["a"] as PoolableComponent1;

			Assert.IsNotNull(other1);
			Assert.IsNotNull(other2);

			Assert.AreSame(inst1, other1);
			Assert.AreSame(inst2, other2);

			kernel.ReleaseComponent(inst2);
			kernel.ReleaseComponent(inst1);
		}
		public void TransientMultipleConstructorNonValueTypeTest()
		{
			DefaultKernel container = new DefaultKernel();
			container.AddComponent("FooBar", typeof(FooBarNonValue));
			Tester1 bla1 = new Tester1("FOOBAR");
			Tester2 bla2 = new Tester2(666);

			Hashtable arguments1 = new Hashtable();
			arguments1.Add("test1", bla1);

			Hashtable arguments2 = new Hashtable();
			arguments2.Add("test2", bla2);

			object a = container.Resolve(typeof(FooBarNonValue), arguments1);
			object b = container.Resolve(typeof(FooBarNonValue), arguments2);

			Assert.AreNotSame(a, b, "A should not be B");

			// multi resolve test

			a = container.Resolve(typeof(FooBarNonValue), arguments1);
			b = container.Resolve(typeof(FooBarNonValue), arguments2);

			Assert.AreNotSame(a, b, "A should not be B");
		}
		public void MaxSize()
		{
			IKernel kernel = new DefaultKernel();
			kernel.AddComponent("a", typeof(PoolableComponent1));

			ArrayList instances = new ArrayList();

			instances.Add(kernel["a"] as PoolableComponent1);
			instances.Add(kernel["a"] as PoolableComponent1);
			instances.Add(kernel["a"] as PoolableComponent1);
			instances.Add(kernel["a"] as PoolableComponent1);
			instances.Add(kernel["a"] as PoolableComponent1);

			PoolableComponent1 other1 = kernel["a"] as PoolableComponent1;

			Assert.IsNotNull(other1);
			Assert.IsTrue(!instances.Contains(other1));

			foreach(object inst in instances)
			{
				kernel.ReleaseComponent(inst);
			}

			kernel.ReleaseComponent(other1);

			PoolableComponent1 other2 = kernel["a"] as PoolableComponent1;
			Assert.IsNotNull(other2);
			Assert.IsTrue(other1 != other2);
			Assert.IsTrue(instances.Contains(other2));

			kernel.ReleaseComponent(other2);
		}
		public void MaxSize()
		{
			IKernel kernel = new DefaultKernel();
			kernel.Register(Component.For(typeof(PoolableComponent1)).Named("a"));

			var instances = new List<PoolableComponent1>
			{
				kernel.Resolve<PoolableComponent1>("a"),
				kernel.Resolve<PoolableComponent1>("a"),
				kernel.Resolve<PoolableComponent1>("a"),
				kernel.Resolve<PoolableComponent1>("a"),
				kernel.Resolve<PoolableComponent1>("a")
			};

			PoolableComponent1 other1 = kernel.Resolve<PoolableComponent1>("a");

			Assert.IsNotNull(other1);
			Assert.IsTrue(!instances.Contains(other1));

			foreach (PoolableComponent1 inst in instances)
			{
				kernel.ReleaseComponent(inst);
			}

			kernel.ReleaseComponent(other1);

			PoolableComponent1 other2 = kernel.Resolve<PoolableComponent1>("a");
			Assert.IsNotNull(other2);
			Assert.IsTrue(other1 != other2);
			Assert.IsTrue(instances.Contains(other2));

			kernel.ReleaseComponent(other2);
		}
		public void TransientMultipleConstructorNonValueTypeTest()
		{
			DefaultKernel container = new DefaultKernel();
			((IKernel)container).Register(Component.For(typeof(FooBarNonValue)).Named("FooBar"));
			Tester1 bla1 = new Tester1("FOOBAR");
			Tester2 bla2 = new Tester2(666);

			var arguments1 = new Dictionary<object, object>();
			arguments1.Add("test1", bla1);

			var arguments2 = new Dictionary<object, object>();
			arguments2.Add("test2", bla2);

			object a = container.Resolve(typeof(FooBarNonValue), arguments1);
			object b = container.Resolve(typeof(FooBarNonValue), arguments2);

			Assert.AreNotSame(a, b, "A should not be B");

			// multi resolve test

			a = container.Resolve(typeof(FooBarNonValue), arguments1);
			b = container.Resolve(typeof(FooBarNonValue), arguments2);

			Assert.AreNotSame(a, b, "A should not be B");
		}
		public void SimpleUsage()
		{
			IKernel kernel = new DefaultKernel();
			kernel.Register(Component.For(typeof(PoolableComponent1)).Named("a"));

			PoolableComponent1 inst1 = kernel.Resolve<PoolableComponent1>("a");
			PoolableComponent1 inst2 = kernel.Resolve<PoolableComponent1>("a");

			Assert.IsNotNull(inst1);
			Assert.IsNotNull(inst2);

			kernel.ReleaseComponent(inst2);
			kernel.ReleaseComponent(inst1);

			PoolableComponent1 other1 = kernel.Resolve<PoolableComponent1>("a");
			PoolableComponent1 other2 = kernel.Resolve<PoolableComponent1>("a");

			Assert.IsNotNull(other1);
			Assert.IsNotNull(other2);

			Assert.AreSame(inst1, other1);
			Assert.AreSame(inst2, other2);

			kernel.ReleaseComponent(inst2);
			kernel.ReleaseComponent(inst1);
		}
        public void Will_give_good_error_message_if_cannot_resolve_service_that_is_likely_decorated()
        {
            DefaultKernel kernel = new DefaultKernel();
            kernel.Register(
                Component.For<IRepository>().ImplementedBy<Repository1>(),
                Component.For<IRepository>().ImplementedBy<DecoratedRepository2>()
                );
            try
            {
                kernel.Resolve<IRepository>();
            }
            catch (HandlerException e)
            {
                const string expectedMessage = @"Can't create component 'Castle.MicroKernel.Tests.ClassComponents.Repository1' as it has dependencies to be satisfied. 
Castle.MicroKernel.Tests.ClassComponents.Repository1 is waiting for the following dependencies: 

Services: 
- Castle.MicroKernel.Tests.ClassComponents.IRepository. 
  A dependency cannot be satisfied by itself, did you forget to add a parameter name to differentiate between the two dependencies? 
 
Castle.MicroKernel.Tests.ClassComponents.DecoratedRepository2 is registered and is matching the required service, but cannot be resolved.

Castle.MicroKernel.Tests.ClassComponents.DecoratedRepository2 is waiting for the following dependencies: 

Keys (components with specific keys)
- name which was not registered. 
";
                Assert.AreEqual(expectedMessage, e.Message);
            }
        }
 public void AddingComponentToRootKernelWhenChildKernelHasStartableFacility()
 {
     IKernel kernel = new DefaultKernel();
     IKernel childKernel = new DefaultKernel();
     kernel.AddChildKernel(childKernel);
     childKernel.AddFacility("StartableFacility", new StartableFacility());
     kernel.AddComponent("string", typeof(String)); // exception here
 }
Exemple #9
0
		public void AddingComponentToRootKernelWhenChildKernelHasStartableFacility()
		{
			IKernel kernel = new DefaultKernel();
			IKernel childKernel = new DefaultKernel();
			kernel.AddChildKernel(childKernel);
			childKernel.AddFacility(new StartableFacility());
			kernel.Register(Component.For(typeof (A)).Named("string")); // exception here
		}
		public void AddingDependencyToServiceWithCustomDependency()
		{
			var kernel = new DefaultKernel();
			kernel.Register(Component.For<NeedClassWithCustomerDependency>(),
			                Component.For<HasCustomDependency>().DependsOn(new Dictionary<object, object> { { "name", new CompA() } }));

			Assert.AreEqual(HandlerState.Valid, kernel.GetHandler(typeof(HasCustomDependency)).CurrentState);
			Assert.IsNotNull(kernel.Resolve(typeof(NeedClassWithCustomerDependency)));
		}
 public void Will_give_good_error_message_if_cannot_resolve_service_that_is_likely_decorated_when_there_are_multiple_service()
 {
     DefaultKernel kernel = new DefaultKernel();
     kernel.Register(
         Component.For<IRepository>().ImplementedBy<Repository1>(),
         Component.For<IRepository>().ImplementedBy<DecoratedRepository2>().Named("foo"),
         Component.For<IRepository>().ImplementedBy<Repository1>().Named("bar")
         );
     kernel.Resolve<IRepository>();
 }
 public void No_context_uses_transient() {
     using (var k = new DefaultKernel()) {
         k.Register(Component.For<Dummy>().LifeStyle.HybridPerWebRequestTransient());
         var d1 = k.Resolve<Dummy>();
         Assert.IsNotNull(d1);
         var d2 = k.Resolve<Dummy>();
         Assert.IsNotNull(d2);
         Assert.AreNotSame(d1, d2);
     }
 }
 public void Should_ignore_reference_to_itself()
 {
     DefaultKernel kernel = new DefaultKernel();
     kernel.Register(
         Component.For<IRepository>().ImplementedBy<Repository1>(),
         Component.For<IRepository>().ImplementedBy<DecoratedRepository>()
         );
     Repository1 repos = (Repository1)kernel.Resolve<IRepository>();
     Assert.IsInstanceOfType(typeof(DecoratedRepository), repos.InnerRepository);
 }
		public void Init()
		{
			kernel = new DefaultKernel();
			kernel.Register(Component.For(typeof(CompA)).Named("compa"));
			kernel.Register(Component.For(typeof(CompB)).Named("compb"));

			deps = new Dictionary<string, object>();
			deps.Add("cc", new CompC(12));
			deps.Add("myArgument", "ernst");
		}
        public void UsingPropertyWithPrivateSetter()
        {
            IKernel container = new DefaultKernel();

            container.AddComponent("service1", typeof(IService1), typeof(Service1));
            container.AddComponent("service2", typeof(IService2), typeof(Service2));

            Service2 service2 = (Service2)container.Resolve<IService2>();

            Assert.IsNull(service2.S,"Kernel should ignore private setter properties");
        }
		public void ContainerShouldUseFirstRegisteredDependencyOfTypeByDefault_SmsRegisteredFirst()
		{
			IKernel kernel = new DefaultKernel();
			kernel.Register(Component.For(typeof(IAlarmSender)).ImplementedBy(typeof(SmsSender)).Named("sms"));
			kernel.Register(Component.For(typeof(IAlarmSender)).ImplementedBy(typeof(EmailSender)).Named("email"));

			kernel.Register(Component.For(typeof(AlarmGenerator)).Named("generator"));

			var gen = kernel.Resolve<AlarmGenerator>("generator");
			Assert.AreEqual(typeof(SmsSender), gen.Sender.GetType());
		}
		public void ContainerShouldUseFirstRegisteredDependencyOfTypeByDefault_EmailRegisteredFirst()
		{
			IKernel kernel = new DefaultKernel();
			kernel.AddComponent("email", typeof(IAlarmSender), typeof(EmailSender));
			kernel.AddComponent("sms", typeof(IAlarmSender), typeof(SmsSender));

			kernel.AddComponent("generator", typeof(AlarmGenerator));

			AlarmGenerator gen = (AlarmGenerator)kernel["generator"];
			Assert.AreEqual(typeof(EmailSender), gen.Sender.GetType());
		}
Exemple #18
0
        public void UsingPropertyWithPrivateSetter()
        {
            IKernel container = new DefaultKernel();

            container.Register(Component.For(typeof(IService1)).ImplementedBy(typeof(Service1)).Named("service1"));
            container.Register(Component.For(typeof(IService2)).ImplementedBy(typeof(Service2)).Named("service2"));

            Service2 service2 = (Service2)container.Resolve<IService2>();

            Assert.IsNull(service2.S,"Kernel should ignore private setter properties");
        }
		public void ChildDependenciesIsSatisfiedEvenWhenComponentTakesLongToBeAddedToParentContainer()
		{
			DefaultKernel container = new DefaultKernel();
			DefaultKernel childContainer = new DefaultKernel();

			container.AddChildKernel(childContainer);
			((IKernel)childContainer).Register(Component.For(typeof(UsesIEmptyService)).Named("component"));

			((IKernel)container).Register(Component.For(typeof(IEmptyService)).ImplementedBy(typeof(EmptyService)).Named("service1"));

			UsesIEmptyService comp = (UsesIEmptyService) childContainer[typeof(UsesIEmptyService)];
		}
		public void ChildDependenciesIsSatisfiedEvenWhenComponentTakesLongToBeAddedToParentContainer()
		{
			DefaultKernel container = new DefaultKernel();
			DefaultKernel childContainer = new DefaultKernel();

			container.AddChildKernel(childContainer);
			childContainer.AddComponent("component", typeof(Component));

			container.AddComponent("service1", typeof(IService), typeof(Service));

			Component comp = (Component) childContainer[typeof(Component)];
		}
		public void ComponentGraph()
		{
			IKernel kernel = new DefaultKernel();
			kernel.AddSubSystem(SubSystemConstants.NamingKey, new NamingPartsSubSystem());

			kernel.AddComponent("common:key1=true", typeof(ICommon), typeof(CommonImpl1));
			kernel.AddComponent("common:secure=true", typeof(ICommon), typeof(CommonImpl2));

			GraphNode[] nodes = kernel.GraphNodes;
			Assert.IsNotNull(nodes);
			Assert.AreEqual(2, nodes.Length);
		}
		public void EmptyDelegateReturnsFirstTypeLoaded()
		{
			IKernel kernel = new DefaultKernel();
			kernel.AddSubSystem(SubSystemConstants.NamingKey, new KeySearchNamingSubSystem());

			kernel.AddComponent("1.common", typeof(ICommon), typeof(CommonImpl1));
			kernel.AddComponent("2.common", typeof(ICommon), typeof(CommonImpl2));

			ICommon common = kernel[typeof(ICommon)] as ICommon;

			Assert.IsNotNull(common);
			Assert.AreEqual(typeof(CommonImpl1), common.GetType());
		}
 public void ResolveInSameSession() {
     var context = GetMockContext();
     var m = new PerWebSessionLifestyleManager {ContextProvider = () => context};
     var kernel = new DefaultKernel();
     var model = new ComponentModel("bla", typeof (object), typeof (object));
     var activator = kernel.CreateComponentActivator(model);
     m.Init(activator, kernel, model);
     var creationContext = new CreationContext(new DefaultHandler(model), kernel.ReleasePolicy, typeof (object), null, null);
     var instance = m.Resolve(creationContext);
     Assert.IsNotNull(instance);
     var instance2 = m.Resolve(creationContext);
     Assert.AreSame(instance, instance2);
 }
		public void GetAssignableHandlers()
		{
			IKernel kernel = new DefaultKernel();
			kernel.AddSubSystem(SubSystemConstants.NamingKey, new NamingPartsSubSystem());

			kernel.AddComponent("common:key1=true", typeof(ICommon), typeof(CommonImpl1));
			kernel.AddComponent("common:secure=true", typeof(ICommon), typeof(CommonImpl2));

			IHandler[] handlers = kernel.GetAssignableHandlers(typeof(ICommon));

			Assert.IsNotNull(handlers);
			Assert.AreEqual(2, handlers.Length);
		}
		public void ServiceLookup()
		{
			IKernel kernel = new DefaultKernel();
			kernel.AddSubSystem(SubSystemConstants.NamingKey, new NamingPartsSubSystem());

			kernel.AddComponent("common:key1=true", typeof(ICommon), typeof(CommonImpl1));
			kernel.AddComponent("common:secure=true", typeof(ICommon), typeof(CommonImpl2));

			ICommon common = kernel[typeof(ICommon)] as ICommon;

			Assert.IsNotNull(common);
			Assert.AreEqual(typeof(CommonImpl1), common.GetType());
		}
		public void When_attemting_to_resolve_component_with_nonpublic_ctor_should_throw_meaningfull_exception()
		{
			var kernel = new DefaultKernel();

			kernel.Register(Component.For<HasProtectedConstructor>());

			Exception exception =
				Assert.Throws<ComponentActivatorException>(() => kernel.Resolve<HasProtectedConstructor>());

			exception = exception.InnerException;
			Assert.IsNotNull(exception);
			StringAssert.Contains("public", exception.Message, "Exception should say that constructor has to be public.");

		}
        public void GetAssignableHandlers()
        {
            IKernel kernel = new DefaultKernel();

            kernel.AddSubSystem(SubSystemConstants.NamingKey, new NamingPartsSubSystem());

            kernel.AddComponent("common:key1=true", typeof(ICommon), typeof(CommonImpl1));
            kernel.AddComponent("common:secure=true", typeof(ICommon), typeof(CommonImpl2));

            IHandler[] handlers = kernel.GetAssignableHandlers(typeof(ICommon));

            Assert.IsNotNull(handlers);
            Assert.AreEqual(2, handlers.Length);
        }
        public void ServiceLookup()
        {
            IKernel kernel = new DefaultKernel();

            kernel.AddSubSystem(SubSystemConstants.NamingKey, new NamingPartsSubSystem());

            kernel.AddComponent("common:key1=true", typeof(ICommon), typeof(CommonImpl1));
            kernel.AddComponent("common:secure=true", typeof(ICommon), typeof(CommonImpl2));

            ICommon common = kernel[typeof(ICommon)] as ICommon;

            Assert.IsNotNull(common);
            Assert.AreEqual(typeof(CommonImpl1), common.GetType());
        }
		public void ReturnsFirstMatchingType()
		{
			IKernel kernel = new DefaultKernel();
			kernel.AddSubSystem(SubSystemConstants.NamingKey,
			                    new KeySearchNamingSubSystem(delegate(string key) { return key.StartsWith("1"); }));

			kernel.AddComponent("1.common", typeof(ICommon), typeof(CommonImpl1));
			kernel.AddComponent("11.common", typeof(ICommon), typeof(CommonImpl2));

			ICommon common = kernel[typeof(ICommon)] as ICommon;

			Assert.IsNotNull(common);
			Assert.AreEqual(typeof(CommonImpl1), common.GetType());
		}
Exemple #30
0
        public void ComponentIdGetsLoadedFromTheParsedConfiguration()
        {
            var     store       = new DefaultConfigurationStore();
            var     interpreter = new XmlInterpreter(Xml.Embedded("sample_config_with_spaces.xml"));
            IKernel kernel      = new DefaultKernel();

            interpreter.ProcessResource(interpreter.Source, store, kernel);

            var container = new WindsorContainer(store);

            var handler = container.Kernel.GetHandler(typeof(ICalcService));

            Assert.AreEqual(Core.LifestyleType.Transient, handler.ComponentModel.LifestyleType);
        }
        public void No_context_uses_transient() {
            var m = new HybridPerWebRequestTransientLifestyleManager();
            var kernel = new DefaultKernel();
            var model = new ComponentModel("bla", typeof(object), typeof(object));
            var activator = kernel.CreateComponentActivator(model);
            m.Init(activator, kernel, model);
            var creationContext = new CreationContext(new DefaultHandler(model), kernel.ReleasePolicy, typeof(object), null, null);
            var instance1 = m.Resolve(creationContext);
            Assert.IsNotNull(instance1);
            var instance2 = m.Resolve(creationContext);
            Assert.IsNotNull(instance2);
            Assert.AreNotSame(instance1, instance2);

        }
        public void TryResolvingViaChildKernelShouldNotThrowException()
        {
            using (var childKernel = new DefaultKernel())
            {
                Kernel.Register(Component.For <BookStore>());
                Kernel.AddChildKernel(childKernel);
                var handler = childKernel.GetHandler(typeof(BookStore));

                // Assert setup invariant
                Assert.IsInstanceOf <ParentHandlerWrapper>(handler);

                Assert.DoesNotThrow(() => handler.TryResolve(CreationContext.CreateEmpty()));
            }
        }
        public void Test_KernelRegister4()
        {
            var context = new ConventionalRegistrationContext(
                Assembly.GetExecutingAssembly(),
                LocalIocManager,
                new ConventionalRegistrationConfig());
            var descriptor = Classes.FromAssembly(context.Assembly);
            var result     = descriptor.BasedOn(new List <Type> {
                typeof(AbpDbContext)
            });
            var kernel = new DefaultKernel();

            ((IRegistration)result).Register(kernel);
        }
        public void When_attemting_to_resolve_component_with_nonpublic_ctor_should_throw_meaningfull_exception()
        {
            var kernel = new DefaultKernel();

            kernel.Register(Component.For <HasProtectedConstructor>());

            Exception exception =
                Assert.Throws <ComponentActivatorException>(() =>
                                                            kernel.Resolve <HasProtectedConstructor>());

            exception = exception.InnerException;
            Assert.IsNotNull(exception);
            StringAssert.Contains("public", exception.Message, "Exception should say that constructor has to be public.");
        }
 public void ResolveInDifferentSessions() {
     var context = GetMockContext();
     var m = new PerWebSessionLifestyleManager {ContextProvider = () => context};
     var kernel = new DefaultKernel();
     var model = new ComponentModel(new ComponentName("bla", true), new List<Type> { typeof(object) }, typeof(object), null);
     var activator = kernel.CreateComponentActivator(model);
     m.Init(activator, kernel, model);
     var creationContext = new Func<CreationContext>(() => new CreationContext(new DefaultHandler(model), kernel.ReleasePolicy, typeof (object), null, null, null));
     var instance = m.Resolve(creationContext(), kernel.ReleasePolicy);
     Assert.IsNotNull(instance);
     context.Session.Abandon();
     var instance2 = m.Resolve(creationContext(), kernel.ReleasePolicy);
     Assert.AreNotSame(instance, instance2);
 }
		public void ReturnsFirstTypeWhenNotFound()
		{
			IKernel kernel = new DefaultKernel();
			kernel.AddSubSystem(SubSystemConstants.NamingKey,
			                    new KeySearchNamingSubSystem(delegate(string key) { return key.StartsWith("3"); }));

			kernel.Register(Component.For(typeof(ICommon)).ImplementedBy(typeof(CommonImpl1)).Named("1.common"));
			kernel.Register(Component.For(typeof(ICommon)).ImplementedBy(typeof(CommonImpl2)).Named("2.common"));

			ICommon common = kernel[typeof(ICommon)] as ICommon;

			Assert.IsNotNull(common);
			Assert.AreEqual(typeof(CommonImpl1), common.GetType());
		}
Exemple #37
0
        public void Test_KernelRegister7()
        {
            var context = new ConventionalRegistrationContext(
                Assembly.GetExecutingAssembly(),
                LocalIocManager,
                new ConventionalRegistrationConfig());
            var descriptor = new FromAssemblyDescriptor(context.Assembly, Classes.MyFilter);
            var result     = new BasedOnDescriptor(new List <Type> {
                typeof(AbpDbContext)
            }, descriptor, Classes.MyFilter);
            var kernel = new DefaultKernel();

            Assert.AreEqual(result.FromDescriptor, descriptor);
            ((IRegistration)result).Register(kernel);
        }
Exemple #38
0
        public void DoesNotDiscoverCircularDependencies()
        {
            var kernel = new DefaultKernel();

            kernel.Resolver.AddSubResolver(new ArrayResolver(kernel));

            // a circular reference exception should be thrown here
            kernel.Register(
                Component.For <Thing>(),
                Component.For <ISubThing>().ImplementedBy <Circular>()
                );

            // this crashes the test framework!
            // var thing = kernel.Resolve<Thing>();
        }
        public void LoadWindsorAssembly()
        {
            IKernel kernel = new DefaultKernel();

            kernel.AddComponent("A", typeof(AssemblyResolverComponent));

            AssemblyResolverComponent comp = (AssemblyResolverComponent)kernel["A"];

            comp.Start();

            Type windsor = Type.GetType(
                "Castle.Windsor.WindsorContainer, Castle.Windsor", false, false);

            Assert.IsNotNull(windsor);
        }
        public void Test_DefaultKernel_AddFacility4()
        {
            var facility = new LoggingFacility();

            facility.LogUsing(LoggerImplementation.NLog).WithConfig("LoggingFacility\\NLog.facilities.test.config");
            var kernel = new DefaultKernel();

            var configuration =
                kernel.ConfigurationStore.GetFacilityConfiguration("LoggingFacility\\NLog.facilities.test.config");

            facility.SetKerenlAndConfig(kernel, configuration);
            facility.SetUpTypeConverter();
            var logApi  = facility.ReadLoggingApi();
            var factory = facility.CreateProperLoggerFactory(logApi);
        }
Exemple #41
0
        public void AddChildKernelToTwoParentsThrowsException()
        {
            var expectedMessage = "You can not change the kernel parent once set, use the RemoveChildKernel and AddChildKernel methods together to achieve this.";

            IKernel kernel2 = new DefaultKernel();

            IKernel subkernel = new DefaultKernel();

            Kernel.AddChildKernel(subkernel);
            Assert.AreEqual(Kernel, subkernel.Parent);

            var exception = Assert.Throws <KernelException>(() => kernel2.AddChildKernel(subkernel));

            Assert.AreEqual(exception.Message, expectedMessage);
        }
Exemple #42
0
        public void Test_MyFacility_SetupConverter()
        {
            IKernel kernel = new DefaultKernel();

            kernel.ConfigurationStore = new DefaultConfigurationStore();
            var configFile = GetConfigFile(LoggerImplementation.ExtendedLog4net);
            Action <LoggingFacility> onCreate = f => f.LogUsing(LoggerImplementation.ExtendedLog4net).WithConfig(configFile);
            var facility = new MyLoggingFacility(kernel, null);

            onCreate.Invoke(facility);
            var converter =
                facility.MyKernel.GetSubSystem(SubSystemConstants.ConversionManagerKey) as IConversionManager;

            Assert.IsNotNull(converter);
        }
Exemple #43
0
        private WindsorContainer CreateContainer()
        {
            var kernel = new DefaultKernel();

            /* Ajout un chargeur pour les classes concrètes. */
            kernel.Register(Component.For <ILazyComponentLoader>().ImplementedBy <ConcreteClassLoader>());

            /* Désactive l'injection des propriétés. */
            kernel.ComponentModelBuilder.RemoveContributor(
                kernel.ComponentModelBuilder.Contributors.OfType <PropertiesDependenciesModelInspector>().Single());

            var container = new WindsorContainer(kernel, new ZeroInstaller());

            return(container);
        }
Exemple #44
0
        public void Test_MyFacility_GetLoggerFactoryType()
        {
            IKernel kernel = new DefaultKernel();

            kernel.ConfigurationStore = new DefaultConfigurationStore();
            var configFile = GetConfigFile(LoggerImplementation.ExtendedLog4net);
            Action <LoggingFacility> onCreate = f => f.LogUsing(LoggerImplementation.ExtendedLog4net).WithConfig(configFile);
            var facility = new MyLoggingFacility(kernel, null);

            onCreate.Invoke(facility);
            facility.SetupConverter();
            var type = facility.GetFactoryType(LoggerImplementation.ExtendedLog4net);

            Assert.IsNotNull(type);
        }
Exemple #45
0
        public void Test_Kernel_AddFacility_WithFullName()
        {
            IKernel kernel = new DefaultKernel();

            kernel.ConfigurationStore = new DefaultConfigurationStore();
            var configFile = GetConfigFile(LoggerImplementation.ExtendedLog4net);
            Action <LoggingFacility> onCreate = f => f.LogUsing(LoggerImplementation.ExtendedLog4net).WithConfig(configFile);
            var facility = new LoggingFacility();

            onCreate.Invoke(facility);
#pragma warning disable 612, 618
            kernel.AddFacility("Castle.Facilities.Logging.LoggingFacility", facility);
#pragma warning restore 612, 618
            Assert.IsNotNull(facility);
        }
        public void ChildDependenciesSatisfiedAmongContainers()
        {
            IKernel subkernel = new DefaultKernel();

            kernel.Register(Component.For(typeof(DefaultTemplateEngine)).Named("templateengine"));
            kernel.Register(Component.For(typeof(DefaultMailSenderService)).Named("mailsender"));

            kernel.AddChildKernel(subkernel);
            subkernel.Register(Component.For(typeof(DefaultSpamService)).Named("spamservice"));

            var spamservice = subkernel.Resolve <DefaultSpamService>("spamservice");

            Assert.IsNotNull(spamservice);
            Assert.IsNotNull(spamservice.MailSender);
            Assert.IsNotNull(spamservice.TemplateEngine);
        }
Exemple #47
0
        public void Test_KernelRegister13()
        {
            var context = new ConventionalRegistrationContext(
                Assembly.GetExecutingAssembly(),
                LocalIocManager,
                new ConventionalRegistrationConfig());
            var descriptor = new FromAssemblyDescriptor(context.Assembly, Classes.MyFilter);
            var result     = new BasedOnDescriptor(new List <Type> {
                typeof(AbpDbContext)
            }, descriptor, Classes.MyFilter);

            descriptor.Criterias.Add(result);
            var kernel = new DefaultKernel();

            result.TryRegister(typeof(MyDbContext), kernel);
        }
Exemple #48
0
        public void Test_KernelRegister16()
        {
            var context = new ConventionalRegistrationContext(
                Assembly.GetExecutingAssembly(),
                LocalIocManager,
                new ConventionalRegistrationConfig());
            var descriptor = new FromAssemblyDescriptor(context.Assembly, Classes.MyFilter);
            var result     = new BasedOnDescriptor(new List <Type> {
                typeof(AbpDbContext)
            }, descriptor, Classes.MyFilter);

            descriptor.Criterias.Add(result);
            var kernel = new DefaultKernel();

            Type[] baseTypes;
            var    type = typeof(MyDbContext);

            Assert.IsTrue(result.Accepts(type, out baseTypes));
            Assert.AreEqual(baseTypes.Length, 1);
            var defaults = CastleComponentAttribute.GetDefaultsFor(type);

            Assert.IsNotNull(defaults);
            var serviceTypes = result.WithService.GetServices(type, baseTypes);

            Assert.AreEqual(serviceTypes.Count, 0);
            Assert.AreEqual(defaults.Services.Length, 1);
            serviceTypes = defaults.Services;
            Assert.AreEqual(serviceTypes.ElementAt(0), typeof(MyDbContext));
            var registration = Component.For(serviceTypes);

            registration.ImplementedBy(type);
            result.Configuration?.Invoke(registration);
            Assert.IsNull(registration.Name);
            Assert.IsNull(defaults.Name);
            registration.RegisterOptionally();

            var token    = kernel.OptimizeDependencyResolution();
            var services = registration.FilterServices(kernel);

            Assert.AreEqual(services.Length, 1);
            Assert.AreEqual(services[0], typeof(MyDbContext));
            var builder            = kernel.ComponentModelBuilder;
            var customContributors = registration.GetContributors(services);
            var componentModel     = builder.BuildModel(customContributors);

            token?.Dispose();
        }
        public void SameLevelDependenciesSatisfied()
        {
            IKernel child = new DefaultKernel();

            kernel.Register(Component.For(typeof(DefaultTemplateEngine)).Named("templateengine"));
            kernel.Register(Component.For(typeof(DefaultSpamService)).Named("spamservice"));

            kernel.AddChildKernel(child);

            child.Register(Component.For(typeof(DefaultMailSenderService)).Named("mailsender"));

            var spamservice = child.Resolve <DefaultSpamService>("spamservice");

            Assert.IsNotNull(spamservice);
            Assert.IsNotNull(spamservice.MailSender);
            Assert.IsNotNull(spamservice.TemplateEngine);
        }
        public void Parent_component_will_NOT_have_dependencies_from_child()
        {
            Kernel.Register(Component.For <DefaultTemplateEngine>(),
                            Component.For <DefaultSpamService>());

            var child = new DefaultKernel();

            Kernel.AddChildKernel(child);

            child.Register(Component.For <DefaultMailSenderService>());

            var spamservice = child.Resolve <DefaultSpamService>();

            Assert.IsNotNull(spamservice);
            Assert.IsNotNull(spamservice.TemplateEngine);
            Assert.IsNull(spamservice.MailSender);
        }
Exemple #51
0
        public void Test_Kenel_GetFacilityConfiguration()
        {
            var kernel = new DefaultKernel();

            kernel.ConfigurationStore = new DefaultConfigurationStore();
            var configFile = GetConfigFile(LoggerImplementation.ExtendedLog4net);
            Action <LoggingFacility> onCreate = f => f.LogUsing(LoggerImplementation.ExtendedLog4net).WithConfig(configFile);
            var facility = new LoggingFacility();

            onCreate.Invoke(facility);
#pragma warning disable 612, 618
            kernel.InsertOneFacility(facility);
#pragma warning restore 612, 618
            var configuration =
                kernel.ConfigurationStore.GetFacilityConfiguration("Castle.Facilities.Logging.LoggingFacility");
            Assert.IsNull(configuration);
        }
Exemple #52
0
        public void Public_property_with_Protected_setter_causes_Object_Reference_exception()
        {
            IKernel kernel = new DefaultKernel();

            kernel.Register(Component.For <Presenter>());
            kernel.Register(Component.For <View>());

            try
            {
                Presenter p = (Presenter)kernel.Resolve(typeof(Presenter));
                Assert.IsNotNull(p);
            }
            catch (NullReferenceException)
            {
                Assert.Fail("Should not have thrown a NullReferenceException");
            }
        }
Exemple #53
0
        public void DependenciesSatisfiedAmongContainers()
        {
            IKernel subkernel = new DefaultKernel();

            kernel.AddComponent("mailsender", typeof(DefaultMailSenderService));
            kernel.AddComponent("templateengine", typeof(DefaultTemplateEngine));

            kernel.AddChildKernel(subkernel);

            subkernel.AddComponent("spamservice", typeof(DefaultSpamService));

            DefaultSpamService spamservice = (DefaultSpamService)subkernel["spamservice"];

            Assert.IsNotNull(spamservice);
            Assert.IsNotNull(spamservice.MailSender);
            Assert.IsNotNull(spamservice.TemplateEngine);
        }
Exemple #54
0
        public void Should_not_fail_when_constructor_parameter_and_public_property_with_private_setter_have_same_name()
        {
            IKernel kernel = new DefaultKernel();

            kernel.Register(Component.For <Service2>());
            kernel.Register(Component.For <Service1>());

            try
            {
                Service2 svc = kernel.Resolve <Service2>();
                Assert.IsNotNull(svc);
            }
            catch (NullReferenceException)
            {
                Assert.Fail("Should not have thrown a NullReferenceException");
            }
        }
Exemple #55
0
        public void SetUp()
        {
            kernel = new DefaultKernel();

            kernel.AddFacility <StartableFacility>();

            kernel.Register(
                Component.For <StartableDisposableAndInitializableComponent>()
                .LifeStyle.Transient
                );

            component = kernel.Resolve <StartableDisposableAndInitializableComponent>();
            component.DoSomething();
            kernel.ReleaseComponent(component);

            calledMethods = component.calledMethods;
        }
Exemple #56
0
        public void TestInterfaceBasedStartable()
        {
            IKernel kernel = new DefaultKernel();

            kernel.AddFacility("startable", new StartableFacility());

            kernel.AddComponent("a", typeof(StartableComponent));

            StartableComponent component = kernel["a"] as StartableComponent;

            Assert.IsNotNull(component);
            Assert.IsTrue(component.Started);
            Assert.IsFalse(component.Stopped);

            kernel.ReleaseComponent(component);
            Assert.IsTrue(component.Stopped);
        }
Exemple #57
0
        public static IKernel Build()
        {
            var kernel = new DefaultKernel();

            kernel.Resolver.AddSubResolver(new CollectionResolver(kernel, true));

            RegisterBackupSources(kernel);
            RegisterCore(kernel);
            RegisterDatabaseProviders(kernel);
            RegisterEmail(kernel);
            RegisterLoggers(kernel);
            RegisterSevenZip(kernel);
            RegisterStorageSources(kernel);
            RegisterUserDataProviders(kernel);

            return(kernel);
        }
Exemple #58
0
        public void ResolveOnceReturnsCorrectResult()
        {
            // Fixture setup
            var kernel    = new DefaultKernel();
            var model     = new ComponentModel("foo", typeof(ICloneable), typeof(Version));
            var activator = kernel.CreateComponentActivator(model);

            var sut = new CacheLifestyleManager();

            sut.Init(activator, kernel, model);
            // Exercise system
            var result = sut.Resolve(CreationContext.Empty);

            // Verify outcome
            Assert.IsAssignableFrom <Version>(result);
            // Teardown
        }
Exemple #59
0
        public void LeaseIsCorrectWhenAccessedAfterInitializationButNoLeaseIsAvailableInKernel()
        {
            // Fixture setup
            var kernel    = new DefaultKernel();
            var model     = new ComponentModel("foo", typeof(ICloneable), typeof(Version));
            var activator = kernel.CreateComponentActivator(model);

            var sut = new CacheLifestyleManager();

            sut.Init(activator, kernel, model);
            // Exercise system
            var result = sut.Lease;
            // Verify outcome
            var actual = Assert.IsAssignableFrom <SlidingLease>(result);

            Assert.Equal(TimeSpan.FromMinutes(1), actual.Timeout);
            // Teardown
        }
Exemple #60
0
        public void ResolveTwiceReturnsSame()
        {
            // Fixture setup
            var kernel    = new DefaultKernel();
            var model     = new ComponentModel("foo", typeof(ICloneable), typeof(Version));
            var activator = kernel.CreateComponentActivator(model);

            var sut = new CacheLifestyleManager();

            sut.Init(activator, kernel, model);
            // Exercise system
            var first  = sut.Resolve(CreationContext.Empty);
            var second = sut.Resolve(CreationContext.Empty);

            // Verify outcome
            Assert.Same(first, second);
            // Teardown
        }