コード例 #1
0
        public async Task Ensure_Registered_Properties_Are_Injected()
        {
            var    collection    = new ServiceCollection();
            string expectedValue = "TestValue";
            string templateKey   = "key";

            collection.AddSingleton(new TestViewModel()
            {
                Title = expectedValue
            });
            var propertyInjector = new PropertyInjector(collection.BuildServiceProvider());

            var builder = new StringBuilder();

            builder.AppendLine("@model object");
            builder.AppendLine("@inject RazorLight.Tests.Models.TestViewModel test");
            builder.AppendLine("Hello @test");

            var engine = new EngineFactory().ForEmbeddedResources(typeof(Root));

            engine.Options.DynamicTemplates.Add(templateKey, builder.ToString());
            ITemplatePage templatePage = await engine.CompileTemplateAsync(templateKey);

            //Act
            propertyInjector.Inject(templatePage);

            //Assert
            var prop = templatePage.GetType().GetProperty("test").GetValue(templatePage);

            Assert.NotNull(prop);
            Assert.IsAssignableFrom <TestViewModel>(prop);
            Assert.Equal((prop as TestViewModel).Title, expectedValue);
        }
コード例 #2
0
        public void Ensure_Registered_Properties_Are_Injected()
        {
            var    collection    = new ServiceCollection();
            string expectedValue = "TestValue";

            collection.AddSingleton(new TestViewModel()
            {
                Title = expectedValue
            });
            var propertyInjector = new PropertyInjector(collection.BuildServiceProvider());

            var builder = new StringBuilder();

            builder.AppendLine("@model object");
            builder.AppendLine("@inject RazorLight.MVC.Tests.TestViewModel test");
            builder.AppendLine("Hello @test");

            IEngineCore       engineCore = new EngineCore(new Templating.Embedded.EmbeddedResourceTemplateManager(typeof(PropertyInjectorTest)));
            CompilationResult result     = engineCore.CompileSource(new Templating.LoadedTemplateSource(builder.ToString()), new ModelTypeInfo(typeof(object)));

            var page = (TemplatePage)Activator.CreateInstance(result.CompiledType);

            propertyInjector.Inject(page);

            var prop = page.GetType().GetProperty("test").GetValue(page);

            Assert.NotNull(prop);
            Assert.IsAssignableFrom <TestViewModel>(prop);
            Assert.Equal((prop as TestViewModel).Title, expectedValue);
        }
コード例 #3
0
        public object Get(Type keyType, params object[] unknownInstances)
        {
            Check.ArgumentIsNull(keyType, nameof(keyType));
            Check.ArgumentIsNull(unknownInstances, nameof(unknownInstances));

            if (unknownInstances.GroupBy(i => i.GetType()).Any(g => g.Count() > 1))
            {
                throw new ArgumentException($"{nameof(unknownInstances)} has more than one entry of the same type.", nameof(unknownInstances));
            }

            var unknownTypes = unknownInstances.ToDictionary(i => i.GetType(), i => i);

            lock (SyncRoot)
            {
                if (!Contains(keyType))
                {
                    throw new ContainerException($"Container does not contain '{keyType}' type as a key.");
                }

                {
                    if (_instances.TryGetValue(keyType, out var instance))
                    {
                        return(instance.Object);
                    }
                }

                {
                    Instance createInstance(ImplementationDefinition implementation)
                    {
                        Check.ArgumentIsNull(implementation, nameof(implementation));

                        switch (implementation)
                        {
                        case ImplementationType implementationType:
                            return(InstanceCreator.Create(this, implementationType.Type, unknownTypes));

                        case ImplementationFactoryMethod implementationFactoryMethod:
                            return(new Instance(implementationFactoryMethod.FactoryMethod(this)));

                        default:
                            throw new InvalidOperationException($"Implementation definition '{implementation.GetType()}' type is not supported.");
                        }
                    }

                    var implementationDefinition = _implementationDefinitions[keyType];
                    var instance = createInstance(implementationDefinition);
                    var obj      = instance.Object;
                    PropertyInjector.Inject(this, instance.Object, unknownTypes);

                    if (implementationDefinition.Lifetime == Lifetime.PerContainer)
                    {
                        _instances.Add(keyType, instance);
                    }

                    return(obj);
                }
            }
        }
コード例 #4
0
        public void Engage()
        {
            foreach (var property in new PropertySelector().Select(context))
            {
                // if the property type is not yet registered throw an exception
                if (!context.Container.IsTypeRegistered(property.PropertyType))
                {
                    throw new TypeResolvingFailedException(Strings.TypeNotRegistered);
                }

                // Engage the value
                var propertyValue = context.Container.Resolve(property.PropertyType);

                // Set the propertys value
                var propertyInjector = new PropertyInjector(property, context, propertyValue);
                propertyInjector.Inject();
            }
        }
コード例 #5
0
        public object CreateInstance(Type type, params object[] unknownInstances)
        {
            Check.ArgumentIsNull(type, nameof(type));
            Check.ArgumentIsNull(unknownInstances, nameof(unknownInstances));

            if (unknownInstances.GroupBy(i => i.GetType()).Any(g => g.Count() > 1))
            {
                throw new ArgumentException($"{nameof(unknownInstances)} has more than one entry of the same type.", nameof(unknownInstances));
            }

            var unknownTypes = unknownInstances.ToDictionary(i => i.GetType(), i => i);

            lock (SyncRoot)
            {
                var instance = InstanceCreator.Create(this, type, unknownTypes);
                PropertyInjector.Inject(this, instance.Object, unknownTypes);

                return(instance.Object);
            }
        }
コード例 #6
0
        public async Task Ensure_Registered_Properties_Are_Injected()
        {
            var    collection    = new ServiceCollection();
            string expectedValue = "TestValue";
            string templateKey   = "key";

            collection.AddSingleton(new TestViewModel {
                Title = expectedValue
            });
            var propertyInjector = new PropertyInjector(collection.BuildServiceProvider());

            var builder = new StringBuilder();

            builder.AppendLine("@model object");
            builder.AppendLine("@inject RazorLight.Tests.Models.TestViewModel test");
            builder.AppendLine("Hello @test");

            var engine = new RazorLightEngineBuilder()
                         .UseEmbeddedResourcesProject(typeof(Root))
                         .SetOperatingAssembly(typeof(Root).Assembly)
                         .AddDynamicTemplates(new Dictionary <string, string> {
                { templateKey, builder.ToString() }
            })
                         .Build();

            ITemplatePage templatePage = await engine.CompileTemplateAsync(templateKey);

            //Act
            propertyInjector.Inject(templatePage);

            //Assert
            var prop = templatePage.GetType().GetProperty("test").GetValue(templatePage);

            Assert.NotNull(prop);
            var model = Assert.IsAssignableFrom <TestViewModel>(prop);

            Assert.Equal(model.Title, expectedValue);
        }