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); }
private static IEnumerable <PropertyInjector> CreatePropertyInjectors(ScopedComponentBase instance) { Type componentType = instance.GetType(); var properties = componentType .GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) .Select(p => new { Property = p, Attribute = p.GetCustomAttribute <InjectScopedAttribute>() }) .Where(x => x.Attribute != null) .Select(x => new { x.Property.PropertyType, x.Property.SetMethod }) .Where(x => x.SetMethod != null); var injectors = new List <PropertyInjector>(); foreach (var property in properties) { var setterDelegateType = typeof(Action <,>).MakeGenericType(componentType, property.PropertyType); var setterDelegate = Delegate.CreateDelegate(setterDelegateType, property.SetMethod); Action <object, object> setProperty = (inst, service) => setterDelegate.DynamicInvoke(inst, service); var injector = new PropertyInjector(property.PropertyType, setProperty); injectors.Add(injector); } return(injectors); }
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); }
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); } } }
public WhenPropertyInjectorIsInvoked() { #if !WINRT property = typeof(Samurai).GetProperty("Weapon"); #else property = typeof(Samurai).GetTypeInfo().GetDeclaredProperty("Weapon"); #endif injector = injectorFactory.Create(property); }
public void CreatesTargetForProperty() { var method = typeof(Dummy).GetProperty("Foo"); PropertyInjector injector = delegate { }; directive = new PropertyInjectionDirective(method, injector); directive.Target.Name.ShouldBe("Foo"); directive.Target.Type.ShouldBe(typeof(int)); }
private static IContainer CreateContainer(Action <ContainerBuilder> build = null) { var builder = new ContainerBuilder(); builder.RegisterModule <ContinuousRunnerModule>(); builder.RegisterAssemblyTypes(typeof(BaseTest).Assembly) .AsImplementedInterfaces() .OnActivated(args => PropertyInjector.InjectProperties(args.Context, args.Instance)); build?.Invoke(builder); return(builder.Build()); }
public void CreatesTargetForProperty() { #if !WINRT var method = typeof(Dummy).GetProperty("Foo"); #else var method = typeof(Dummy).GetRuntimeProperty("Foo"); #endif PropertyInjector injector = delegate { }; directive = new PropertyInjectionDirective(method, injector); directive.Target.Name.Should().Be("Foo"); directive.Target.Type.Should().Be(typeof(int)); }
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(); } }
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); } }
public WhenActivateIsCalled() { contextMock = new Mock<IContext>(); planMock = new Mock<IPlan>(); injector1 = (x, y) => { injector1WasCalled = true; }; injector2 = (x, y) => { injector2WasCalled = true; }; directives = new[] { new FakePropertyInjectionDirective(property1, injector1), new FakePropertyInjectionDirective(property2, injector2) }; contextMock.SetupGet(x => x.Plan).Returns(planMock.Object); contextMock.SetupGet(x => x.Parameters).Returns(new IParameter[0]); reference = new InstanceReference { Instance = instance }; planMock.Setup(x => x.GetAll<PropertyInjectionDirective>()).Returns(directives); }
public WhenActivateIsCalled() { contextMock = new Mock <IContext>(); planMock = new Mock <IPlan>(); injector1 = (x, y) => { injector1WasCalled = true; }; injector2 = (x, y) => { injector2WasCalled = true; }; directives = new[] { new FakePropertyInjectionDirective(property1, injector1), new FakePropertyInjectionDirective(property2, injector2) }; contextMock.SetupGet(x => x.Plan).Returns(planMock.Object); contextMock.SetupGet(x => x.Parameters).Returns(new IParameter[0]); reference = new InstanceReference { Instance = instance }; planMock.Setup(x => x.GetAll <PropertyInjectionDirective>()).Returns(directives); }
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); }
public FakePropertyInjectionDirective(PropertyInfo property, PropertyInjector injector) : base(property, injector) { }
public WhenPropertyInjectorIsInvoked() { property = typeof(Samurai).GetProperty("Weapon"); injector = injectorFactory.Create(property); }
/// <summary> /// Initializes a new instance of the <see cref="PropertyInjectionDirective" /> class. /// </summary> /// <param name="member">The member the directive describes.</param> /// <param name="injector">The injector that will be triggered.</param> public PropertyInjectionDirective(PropertyInfo member, PropertyInjector injector) { Injector = injector; Target = CreateTarget(member); }
/// <summary> /// Initializes a new instance of the <see cref="PropertyInjectionDirective"/> class. /// </summary> /// <param name="member">The member the directive describes.</param> /// <param name="injector">The injector that will be triggered.</param> public PropertyInjectionDirective(PropertyInfo member, PropertyInjector injector) { this.Injector = injector; this.Target = this.CreateTarget(member); }
/// <summary> /// Initializes a new instance of the <see cref="PropertyInjectionDirective"/> class. /// </summary> /// <param name="member">The member the directive describes.</param> /// <param name="injector">The injector that will be triggered.</param> public PropertyInjectionDirective(PropertyInfo member, PropertyInjector injector) { Injector = injector; Target = CreateTarget(member); }
/// <summary> /// Initializes a new instance of the <see cref="PropertyDirective"/> class. /// </summary> /// <param name="member">The member the directive describes.</param> /// <param name="injector">The injector that will be triggered.</param> public PropertyDirective(PropertyInfo member, PropertyInjector injector) : base(member, injector) { }
public WhenPropertyInjectorIsInvoked() { this.property = typeof(Samurai).GetProperty("Weapon"); this.injector = this.injectorFactory.Create(this.property); }