An Spring.Context.IApplicationContext implementation that reads context definitions from XML based resources.

Currently, the resources that are supported are the file, http, ftp, config and assembly resource types.

You can provide custom implementations of the Spring.Core.IO.IResource interface and and register them with any Spring.Context.IApplicationContext that inherits from the Spring.Context.Support.AbstractApplicationContext interface.

In case of multiple config locations, later object definitions will override ones defined in previously loaded resources. This can be leveraged to deliberately override certain object definitions via an extra XML file.
Наследование: Spring.Context.Support.AbstractXmlApplicationContext
Пример #1
0
        public void ContainerResolvesSauceBéarnaiseThroughType()
        {
            var context = new XmlApplicationContext("sauce.xml");
            SauceBéarnaise sauce = context.GetObjectsOfType(typeof(SauceBéarnaise)).Values.OfType<SauceBéarnaise>().Single();

            Assert.NotNull(sauce);
        }
Пример #2
0
        private static IApplicationContext GetApplicationContextForConfigurationFile(string configurationFile)
        {
            using (TimedLock.Lock(LoadedContexts))
            {
                IApplicationContext context;
                if (LoadedContexts.TryGetValue(configurationFile, out context))
                    return context;

                List<string> springFilesToLoad = new List<string>();
                foreach (string springFile in File.ReadAllLines("SpringFiles.txt"))
                    springFilesToLoad.Add("file://" + springFile);

                // Get all of the plugins
                foreach (string pluginFilename in Directory.GetFiles(".", "Plugin.*.xml"))
                    springFilesToLoad.Add("file://" + pluginFilename);

                // Load objects declared in Spring
                context = new XmlApplicationContext(springFilesToLoad.ToArray());

                // Load configuration file for options that can be set up in simplified XML
                ConfigurationFileReader.ReadConfigFile(context, configurationFile);

                LoadedContexts[configurationFile] = context;

                return context;
            }
        }
Пример #3
0
        public void ContainerResolvesSauceBéarnaiseThroughExtensionMethod()
        {
            var context = new XmlApplicationContext("sauce.xml");
            SauceBéarnaise sauce = context.Resolve<SauceBéarnaise>();

            Assert.NotNull(sauce);
        }
Пример #4
0
        public void ContainerResolvesIngredientThroughExtensionMethod()
        {
            var context = new XmlApplicationContext("sauce.xml");
            IIngredient ingredient = context.Resolve<IIngredient>();

            Assert.IsAssignableFrom<SauceBéarnaise>(ingredient);
        }
        /// <summary>
        /// Metodo que retorna la informacion de los insumos para generar las plantillas de estado de cuenta.
        /// </summary>
        /// <param name="IdConcesionario"></param>
        /// <param name="fecha"></param>
        /// <returns></returns>
        public System.Data.DataTable ObtenerInsumosPlantilla(decimal IdConcesionario, DateTime fecha)
        {
            DataTable insumo;
            try
            {
                IApplicationContext contexto = new XmlApplicationContext("DataConfiguration.xml");
                this.ConsultaDatos = (IConsultasPlantillaDB)contexto.GetObject("DaoConsulta");

                insumo = this.ConsultaDatos.ObtenerInsumosPlantilla(IdConcesionario, fecha);

            }
            catch (ExcepcionDatosEstadoCuenta excepcion)
            {
                throw excepcion;
            }
            catch (Exception excepcion)
            {
                string mensajeError = "Error presentado en la clase LogicaDatosEstadoCuenta en el método ObtenerInsumosPlantilla" +
                                      ". Detalle del error: " + excepcion.Message;

                throw new ExcepcionLogicaEstadoCuenta(mensajeError, excepcion);
            }

            return insumo;
        }
        public void UseSpecifiedObjectNameGenerator()
        {
            _applicationContext = new XmlApplicationContext(ReadOnlyXmlTestResource.GetFilePath("ConfigFiles.ComponentScan3.xml", GetType()));
            var objectDefinitionNames = _applicationContext.ObjectFactory.GetObjectDefinitionNames();

            Assert.That(objectDefinitionNames.Contains("prototype"), Is.True);
        }
Пример #7
0
        public ActionResult GetMenu()
        {
            //TODO Eliminar cuando se descubra una mejor forma
            IApplicationContext appContext =
                new XmlApplicationContext(HttpContext.Server.MapPath(@"~/Config/service.xml"),
                    HttpContext.Server.MapPath(@"~/Config/repository.xml"));
            UsuarioService = (IUsuarioService)appContext.GetObject("UsuarioService");
            PerfilMenuService = (IPerfilMenuService)appContext.GetObject("PerfilMenuService");
            //

            List<Usuario> ListUsuario = UsuarioService.ReadUsuarioByUsername(User.Identity.Name).ToList();
            Usuario usuario = (Usuario)ListUsuario[0];
            IList<PerfilMenu> ListPM = PerfilMenuService.ReadPerfilMenuByPerfilId(usuario.PerfilId).ToList();
            IList<Menu> items = new List<Menu>();

            foreach (PerfilMenu pm in ListPM)
            {
                pm.Menu.Activo = pm.Activo;
                items.Add(pm.Menu);
            }

            MenuViewModel menuViewModel = new MenuViewModel(items, usuario);

            return PartialView("_Nav", menuViewModel);
        }
 public void Setup() {
     appContext = new XmlApplicationContext(false,
                                            ReadOnlyXmlTestResource.GetFilePath(
                                                "VelocityEngineFactoryObjectTests.xml",
                                                typeof(VelocityEngineFactoryObjectTests)));
     model.Add("var1", TEST_VALUE);
 }
Пример #9
0
 public void Main()
 {
     var ctx = new XmlApplicationContext("objects.xml");
     var o1 = ctx.GetObject("SingletonObject");
     var o2 = ctx.GetObject("ProtoTypeObject");
     ctx.Dispose();
 }
Пример #10
0
        private static void Main(string[] args)
        {
            DeleteDatabase();

            _ctx = new XmlApplicationContext("objects.xml");
            try
            {
                PrintUsers();

                InsertUser("Marijn");

                PrintUsers();

                InsertUser("Iris");

                PrintUsers();

                Console.WriteLine();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            Console.WriteLine("Any key to exit ...");
            Console.ReadLine();
        }
        //[Test]
        public void CustomProperties()
        {
            NamespaceParserRegistry.RegisterParser(typeof(WcfNamespaceParser));
            IApplicationContext ctx = new XmlApplicationContext(
                ReadOnlyXmlTestResource.GetFilePath("ChannelFactoryObjectDefinitionParserTests.CustomProperties.xml", this.GetType()));

            Assert.IsTrue(ctx.ContainsObjectDefinition("channel"));

            RootObjectDefinition rod = ((IObjectDefinitionRegistry)ctx).GetObjectDefinition("channel") as RootObjectDefinition;
            Assert.IsNotNull(rod);

            Assert.IsTrue(rod.HasObjectType);
            Assert.AreEqual(typeof(ChannelFactoryObject<IContract>), rod.ObjectType);
            Assert.AreEqual(1, rod.ConstructorArgumentValues.NamedArgumentValues.Count);
            Assert.AreEqual("ecn", rod.ConstructorArgumentValues.GetNamedArgumentValue("endpointConfigurationName").Value);
            Assert.IsTrue(rod.PropertyValues.Contains("Credentials.Windows.ClientCredential"));
            Assert.AreEqual("Spring\\Bruno:gnirpS", rod.PropertyValues.GetPropertyValue("Credentials.Windows.ClientCredential").Value);

            ChannelFactoryObject<IContract> cfo = ctx.GetObject("&channel") as ChannelFactoryObject<IContract>;
            Assert.IsNotNull(cfo);
            Assert.AreEqual(typeof(IContract), cfo.ObjectType);
            Assert.AreEqual("Spring", cfo.Credentials.Windows.ClientCredential.Domain);
            Assert.AreEqual("Bruno", cfo.Credentials.Windows.ClientCredential.UserName);
            Assert.AreEqual("gnirpS", cfo.Credentials.Windows.ClientCredential.Password);

            IContract contract = ctx.GetObject("channel") as IContract;
            Assert.IsNotNull(contract);
        }
        public void TestAutoProxyCreation()
        {
            XmlApplicationContext context = new XmlApplicationContext(ReadOnlyXmlTestResource.GetFilePath("advisorAutoProxyCreatorCircularReferencesTests.xml", typeof(AdvisorAutoProxyCreatorCircularReferencesTests)));
            CountingAfterReturningAdvisor countingAdvisor = (CountingAfterReturningAdvisor)context.GetObject("testAdvisor");

            // direct deps of AutoProxyCreator are not eligable for proxying
            Assert.IsFalse(AopUtils.IsAopProxy(context.GetObject("aapc")));
            Assert.IsFalse(AopUtils.IsAopProxy(countingAdvisor));

            TestObjectFactoryObject testObjectFactory = (TestObjectFactoryObject) context.GetObject("&testObjectFactory");
            Assert.IsFalse(AopUtils.IsAopProxy(testObjectFactory));

            Assert.IsFalse(AopUtils.IsAopProxy(context.GetObject("someOtherObject")));

            // this one is completely independent
            Assert.IsTrue(AopUtils.IsAopProxy(context.GetObject("independentObject")));


            // Asserts SPRNET-1225 - advisor dependencies most not be auto-proxied
            object testObject = context.GetObject("testObjectFactory");
            Assert.IsFalse(AopUtils.IsAopProxy(testObject));

            // Asserts SPRNET-1224 - factory product most be cached
            context.GetObject("testObjectFactory");
            testObjectFactory.GetObjectCounter = 0;
            context.GetObject("testObjectFactory");
            Assert.AreEqual(0, testObjectFactory.GetObjectCounter);

            ICloneable someOtherObject = (ICloneable) context.GetObject("someOtherObject");
            someOtherObject.Clone();
            ICloneable independentObject = (ICloneable) context.GetObject("independentObject");
            independentObject.Clone();
            Assert.AreEqual(1, countingAdvisor.GetCalls());
        }
        public void ShouldGetBacklogDistribution()
        {
            IApplicationContext context = new XmlApplicationContext(_config);

            IProbabilityDistribution backlogdist = (IProbabilityDistribution)context.GetObject("backlogdist");
            Assert.AreEqual(2, backlogdist.NextValue());
        }
Пример #14
0
        public void ContainerResolvesSauceBéarnaise()
        {
            var context = new XmlApplicationContext("sauce.xml");
            SauceBéarnaise sauce = (SauceBéarnaise)context.GetObject("Sauce");

            Assert.NotNull(sauce);
        }
        public void ShouldGetResourcePool()
        {
            IApplicationContext context = new XmlApplicationContext(_config);

            ResourcePool resourcePool = (ResourcePool)context.GetObject("rp1");

            Assert.AreEqual(1,resourcePool.ResourceCount);
        }
Пример #16
0
        public void ContainerLoadsXmlFromEmbeddedResource()
        {
            var context = new XmlApplicationContext("assembly://Ploeh.Samples.Menu.SpringNet/Ploeh.Samples.Menu.SpringNet/sauce.xml");
            SauceBéarnaise sauce =
                (SauceBéarnaise)context.GetObject("Sauce");

            Assert.NotNull(sauce);
        }
Пример #17
0
        public void ContainerLoadsXmlFromConfig()
        {
            var context = new XmlApplicationContext("config://spring/objects");
            SauceBéarnaise sauce =
                (SauceBéarnaise)context.GetObject("Sauce");

            Assert.NotNull(sauce);
        }
Пример #18
0
        public void ContainerLoadsXmlFromFileMoniker()
        {
            var context = new XmlApplicationContext("file://sauce.xml");
            SauceBéarnaise sauce =
                (SauceBéarnaise)context.GetObject("Sauce");

            Assert.NotNull(sauce);
        }
        public void ShouldGetWorkStation()
        {
            IApplicationContext context = new XmlApplicationContext(_config);

            IWorkStation ws = (IWorkStation)context.GetObject("ws1");

            Assert.IsNotNull(ws);
        }
Пример #20
0
 public void CreateDbProvider()
 {
     IApplicationContext ctx =
         new XmlApplicationContext("assembly://Spring.Data.Integration.Tests/Spring.Data/adoTemplateTests.xml");
     Assert.IsNotNull(ctx);
     dbProvider = ctx["DbProvider"] as IDbProvider;
     Assert.IsNotNull(dbProvider);
 }
Пример #21
0
 private static void PrintOutNameAndConnection(XmlApplicationContext ctx)
 {
     foreach (var name in ctx.GetObjectNamesForType(typeof (MyService)))
     {
         var svc = (MyService) ctx.GetObject(name);
         Console.WriteLine("{0} : {1}", name, svc.Connection);
     }
 }
Пример #22
0
        public void Main()
        {
            var ctx = new XmlApplicationContext("objects.xml","objects2.xml");
            var o = (MyClass)ctx.GetObject("MyObject");

            Assert.AreEqual("From objects2.xml", o.Name);
            Console.WriteLine(o);
        }
        public void ShouldGetMachine()
        {
            IApplicationContext context = new XmlApplicationContext(_config);

            Machine machine = (Machine)context.GetObject("machine1");

            Assert.IsNotNull(machine);
        }
        public void ShouldGetWorkProcess()
        {
            IApplicationContext context = new XmlApplicationContext(_config);

            WorkProcess backlog = (WorkProcess)context.GetObject("process");

            Assert.IsNotNull(backlog);
        }
Пример #25
0
        public void SingleConfigLocation()
        {
            XmlApplicationContext ctx =
                new XmlApplicationContext(false, "assembly://Spring.Core.Tests/Spring.Context.Support/simpleContext.xml");

            Assert.IsTrue(ctx.ContainsObject("someMessageSource"));
            ctx.Dispose();
        }
Пример #26
0
 public void Main()
 {
     var ctx = new XmlApplicationContext("abstract-factory.xml");
     var o = (Consumer)ctx.GetObject("consumer");
     Assert.AreEqual("Illnois", o.Process("Illnois"));
     Assert.AreEqual("aksalA", o.Process("Alaska"));
     Assert.AreEqual("nisnocsiW", o.Process("Wisconsin"));
 }
Пример #27
0
        public void ContextWithInvalidLazyType()
        {
            XmlApplicationContext ctx =
                new XmlApplicationContext(false,
                                          "assembly://Spring.Core.Tests/Spring.Context.Support/invalidType.xml");

            Assert.IsTrue(ctx.ContainsObject("someMessageSource"));
            ctx.GetObject("someMessageSource");
        }
Пример #28
0
        public void GetObjectOnUnknownIdThrowsNoSuchObjectDefinition()
        {
            XmlApplicationContext ctx =
                new XmlApplicationContext(false, "assembly://Spring.Core.Tests/Spring.Context.Support/objects.xml");
            string DOES_NOT_EXIST = "does_not_exist";

            Assert.IsFalse(ctx.ContainsObject(DOES_NOT_EXIST));
            Assert.Throws <NoSuchObjectDefinitionException>(() => ctx.GetObject(DOES_NOT_EXIST));
        }
Пример #29
0
	    public void SimpleCreate()
	    {
            IApplicationContext ctx =
                new XmlApplicationContext("assembly://Spring.Data.Integration.Tests/Spring.Data/nativeAdoTests.xml");
            Assert.IsNotNull(ctx);
            ITestObjectDao dao = (ITestObjectDao)ctx["testObjectDao"];
            Assert.IsNotNull(dao);
            dao.Create("John", 44);
	    }
        public void TestReceivesMessageFromChannelWithSource()
        {
            NamespaceParserRegistry.RegisterParser(typeof (IntegrationNamespaceParser));

            IApplicationContext ctx = new XmlApplicationContext(@"Channel\Config\DirectChannelParserTests.xml");

            object channel = ctx.GetObject("channel");
            Assert.That(channel.GetType(), Is.EqualTo(typeof (DirectChannel)));
        }
        public void testRendezvous()
        {
            NamespaceParserRegistry.RegisterParser(typeof (IntegrationNamespaceParser));

            IApplicationContext ctx = new XmlApplicationContext(@"Channel\Config\RendezvousChannelParserTests.xml");

            object channel = ctx.GetObject("channel");
            Assert.That(channel.GetType(), Is.EqualTo(typeof (RendezvousChannel)));
        }
Пример #32
0
        public void Main()
        {
            var ctx = new XmlApplicationContext("objects.xml");
            var o = (MyClass)ctx.GetObject("MyObject");

            o.Method1();

            Console.WriteLine(o);
        }
 public void CreateAdoTemplate()
 {
     IApplicationContext ctx =
         new XmlApplicationContext("assembly://Spring.Data.Integration.Tests/Spring.Data/adoTemplateTests.xml");
     Assert.IsNotNull(ctx);
     adoTemplate = ctx["adoTemplate"] as AdoTemplate;
     Assert.IsNotNull(adoTemplate);
     //CleanDb();
 }
Пример #34
0
        public void CaseInsensitiveContext()
        {
            XmlApplicationContext ctx =
                new XmlApplicationContext(false, "assembly://Spring.Core.Tests/Spring.Context.Support/objects.xml");

            Assert.IsTrue(ctx.ContainsObject("goran"));
            Assert.IsTrue(ctx.ContainsObject("Goran"));
            Assert.IsTrue(ctx.ContainsObject("GORAN"));
            Assert.AreEqual(ctx.GetObject("goran"), ctx.GetObject("GORAN"));
        }
Пример #35
0
        private static AbstractApplicationContext CreateAppContext(AbstractApplicationContext configurationContext)
        {
            var containerArgs = new XmlApplicationContextArgs()
            {
                CaseSensitive          = true,
                Name                   = "root",
                ConfigurationLocations = new[] { "assembly://DevWeek.Worker/DevWeek/Container.Config.xml" },
                ParentContext          = configurationContext
            };
            var appContext = new Spring.Context.Support.XmlApplicationContext(containerArgs);

            return(appContext);
        }
Пример #36
0
        public void ContextWithPostProcessors()
        {
            CountingObjectPostProcessor.Count       = 0;
            CoutingObjectFactoryPostProcessor.Count = 0;

            IApplicationContext ctx =
                new XmlApplicationContext("assembly://Spring.Core.Tests/Spring.Context.Support/objects.xml");

            Assert.IsTrue(ctx.ContainsObject("abstractObjectProcessorPrototype"));
            Assert.IsTrue(ctx.ContainsObject("abstractFactoryProcessorPrototype"));

            Assert.AreEqual(0, CountingObjectPostProcessor.Count);
            Assert.AreEqual(0, CoutingObjectFactoryPostProcessor.Count);
        }
Пример #37
0
 public void ContextWithInvalidValueType()
 {
     try
     {
         XmlApplicationContext ctx =
             new XmlApplicationContext(false,
                                       "assembly://Spring.Core.Tests/Spring.Context.Support/invalidValueType.xml");
         Assert.Fail("Should have thrown ObjectCreationException for context", ctx);
     }
     catch (ObjectCreationException ex)
     {
         Assert.IsTrue(ex.Message.IndexOf((typeof(TypeMismatchException).Name)) != -1);
         Assert.IsTrue(ex.Message.IndexOf(("UseCodeAsDefaultMessage")) != -1);
     }
 }
Пример #38
0
 public void InnerObjectWithPostProcessing()
 {
     try
     {
         XmlApplicationContext ctx = new XmlApplicationContext(false, "assembly://Spring.Core.Tests/Spring.Context.Support/innerObjectsWithPostProcessor.xml");
         ctx.GetObject("hasInnerObjects");
         Assert.Fail("should throw ObjectCreationException");
     }
     catch (ObjectCreationException e)
     {
         NoSuchObjectDefinitionException ex = e.InnerException as NoSuchObjectDefinitionException;
         Assert.IsNotNull(ex);
         //Pass
     }
 }
Пример #39
0
        public void MultipleConfigLocations()
        {
            XmlApplicationContext ctx =
                new XmlApplicationContext(false, "assembly://Spring.Core.Tests/Spring.Context.Support/contextB.xml",
                                          "assembly://Spring.Core.Tests/Spring.Context.Support/contextC.xml",
                                          "assembly://Spring.Core.Tests/Spring.Context.Support/contextA.xml");

            Assert.IsTrue(ctx.ContainsObject("service"));
            Assert.IsTrue(ctx.ContainsObject("logicOne"));
            Assert.IsTrue(ctx.ContainsObject("logicTwo"));
            Service service = (Service)ctx.GetObject("service");

            ctx.Refresh();
            Assert.IsTrue(service.ProperlyDestroyed);
            service = (Service)ctx.GetObject("service");
            ctx.Dispose();
            Assert.IsTrue(service.ProperlyDestroyed);
        }
        public void ConfigureUsingXmlApplicationContext()
        {
            XmlApplicationContext appContext = new XmlApplicationContext(false, ReadOnlyXmlTestResource.GetFilePath("HttpApplicationConfigurerTests.xml", typeof(HttpApplicationConfigurerTests)));

            TestModule m1 = new TestModule();
            TestModule m2 = new TestModule();

            TestApplication appObject = new TestApplication(new ModuleEntry[]
            {
                new ModuleEntry("TestModule1", m1)
                , new ModuleEntry("TestModule2", m2),
            });

            HttpApplicationConfigurer.Configure(appContext, appObject);
            // app configured
            Assert.AreEqual(appContext.GetObject("testObject"), appObject.TestObject);
            // modules configured
            Assert.AreEqual(appContext.GetObject("testObject1"), m1.TestObject);
            Assert.AreEqual(null, m2.TestObject);
        }
Пример #41
0
        public void RefreshDisposesExistingObjectFactory_SPRNET479()
        {
            string tmp = typeof(DestroyTester).FullName;

            Console.WriteLine(tmp);

            IApplicationContext ctx =
                new XmlApplicationContext("assembly://Spring.Core.Tests/Spring.Context.Support/objects.xml");

            DestroyTester destroyTester = (DestroyTester)ctx.GetObject("destroyTester");
            DisposeTester disposeTester = (DisposeTester)ctx.GetObject("disposeTester");

            Assert.IsFalse(destroyTester.IsDestroyed);
            Assert.IsFalse(disposeTester.IsDisposed);

            ((IConfigurableApplicationContext)ctx).Refresh();

            Assert.IsTrue(destroyTester.IsDestroyed);
            Assert.IsTrue(disposeTester.IsDisposed);
        }
Пример #42
0
        public void ContextLifeCycle()
        {
            IApplicationContext ctx =
                new XmlApplicationContext("assembly://Spring.Core.Tests/Spring.Context/contextlifecycle.xml");
            IConfigurableApplicationContext configCtx = ctx as IConfigurableApplicationContext;

            Assert.IsNotNull(configCtx);
            ContextListenerObject clo;

            using (configCtx)
            {
                clo = configCtx["contextListenerObject"] as ContextListenerObject;
                Assert.IsNotNull(clo);
                Assert.IsTrue(clo.AppListenerContextRefreshed,
                              "Object did not receive context refreshed event via IApplicationListener");
                Assert.IsTrue(clo.CtxRefreshed, "Object did not receive context refreshed event via direct wiring");
            }
            Assert.IsTrue(clo.AppListenerContextClosed,
                          "Object did not receive context closed event via IApplicationContextListener");
            Assert.IsTrue(clo.CtxClosed, "Object did not receive context closed event via direct wiring.");
        }
Пример #43
0
        public void ConfigureObject()
        {
            const string objDefLocation = "assembly://Spring.Core.Tests/Spring.Context.Support/objects.xml";

            XmlApplicationContext xmlContext = new XmlApplicationContext(new string[] { objDefLocation });

            object objGoran = xmlContext.GetObject("goran");

            Assert.IsTrue(objGoran is TestObject);
            TestObject fooGet = objGoran as TestObject;

            TestObject fooConfigure = new TestObject();

            xmlContext.ConfigureObject(fooConfigure, "goran");
            Assert.IsNotNull(fooGet);
            Assert.AreEqual(fooGet.Name, fooConfigure.Name);
            Assert.AreEqual(fooGet.Age, fooConfigure.Age);
            Assert.AreEqual(fooGet.ObjectName, fooConfigure.ObjectName);
            Assert.IsNotNull(fooGet.ObjectName);
            Assert.AreEqual(xmlContext, fooGet.ApplicationContext);
            Assert.AreEqual(xmlContext, fooConfigure.ApplicationContext);
        }
Пример #44
0
 public void SPRNET1231_DoesNotInvokeFactoryMethodDuringObjectFactoryPostProcessing()
 {
     string configLocation     = TestResourceLoader.GetAssemblyResourceUri(this.GetType(), "XmlApplicationContextTests-SPRNET1231.xml");
     XmlApplicationContext ctx = new XmlApplicationContext(configLocation);
 }