public void Singleton_GenericTypeNotAnInterface_InvalidOperationException() { using (var context = new InjectionContext()) { Assert.Throws <InvalidOperationException>(() => context.Singleton(c => new TestClass())); } }
protected override object Inject(ref InjectionContext context) { var value = context.Container.Resolver.Resolve(context); wrapper.Set(ref context.Instance, value); return value; }
public override TDependency Resolve(InjectionContext context) { object instance; MyBuilder.BuildInstance(context, null, out instance); return(MapInstance(instance)); }
public void TryGet_ClassWithNonPublicConstructor_Null() { using (var context = new InjectionContext()) { Assert.IsNull(context.TryGet <TestClassWithNonPublicConstructor>()); } }
public void Get_ClassWithNonPublicConstructor_ThrowsInvalidOperationException() { using (var context = new InjectionContext()) { Assert.Throws <InvalidOperationException>(() => context.Get <TestClassWithNonPublicConstructor>()); } }
IBinding GetBinding(ref InjectionContext context) { if (context.ContractType == null) return null; return context.Container.Binder.GetBinding(context); }
public void TryGet_InterfaceNotRegistered_Null() { using (var context = new InjectionContext()) { Assert.IsNull(context.TryGet <ITestInterface>()); } }
public override object Resolve(InjectionContext context) { object instance; MyBuilder.BuildInstance(context, null, out instance); return(instance); }
public object Create(InjectionContext context) { context.Instance = method(context); context.Container.Injector.Inject(context); return(context.Instance); }
IInjectableConstructor GetConstructor(ref InjectionContext context) { if (context.DeclaringType == null || !context.DeclaringType.IsConcrete()) return null; return selector.Select(context, context.Container.Analyzer.GetAnalysis(context.DeclaringType).Constructors); }
object[] MergePositionalParameters(InjectionContext context, ParameterSet myParams) { var paramLength = myParams.Length - 1; var result = new object[_ctorDependencyProviders.Length]; for (var i = 0; i < _ctorDependencyProviders.Length; i++) { var depProvider = _ctorDependencyProviders[i]; if (i > paramLength) { if (depProvider.IsAutowirable) { depProvider.CreateObject(context, out result[i]); } else { throw ParameterException.NonautowirableParameterNotSpecified(context, depProvider, i); } } else { var providedParam = myParams[i]; if (providedParam.CanSupplyValueFor(depProvider)) { result[i] = providedParam.ParameterValue; } else { depProvider.CreateObject(context, out result[i]); } } } return(result); }
public void Get_InterfaceNotRegistered_ThrowsInvalidOperationException() { using (var context = new InjectionContext()) { Assert.Throws <InvalidOperationException>(() => context.Get <ITestInterface>()); } }
private void InsertTable(InjectionContext injectionContext) { var markerPosition = injectionContext.MarkerRange.StartMarker.Position; var table = (injectionContext.Injection as TableInjection).Resource.Object; var sheet = injectionContext.Workbook.Worksheet(markerPosition.SheetIndex); var topLeftCell = sheet.Cell(markerPosition.RowIndex, markerPosition.CellIndex); var rowCount = table.Count; var columnCount = rowCount == 0 ? 0 : table[0].Count; //удаляем маркер if (rowCount == 0 || columnCount == 0) { topLeftCell.Clear(XLClearOptions.Contents); } var mergedRowsEnumerator = CellUtils.EnumerateMergedRows(topLeftCell).GetEnumerator(); table.ForEach(dataRow => { mergedRowsEnumerator.MoveNext(); var excelRow = mergedRowsEnumerator.Current; var firstCellOfRow = sheet.Cell(excelRow.FirstCell().Address.RowNumber, topLeftCell.Address.ColumnNumber); var mergedCellsEnumerator = CellUtils.EnumerateMergedCells(firstCellOfRow).GetEnumerator(); dataRow.ForEach(dataValue => { mergedCellsEnumerator.MoveNext(); CellUtils.SetDynamicCellValue(mergedCellsEnumerator.Current, dataValue); }); }); }
/// <summary> /// Creates an instance of the object of the type created by the factory. /// </summary> /// <param name="context">Injection context.</param> /// <returns>The instance.</returns> public object Create(InjectionContext context) { // Resolve a cube. var cube = this.container.Resolve <Cube>(); // Add the "Rotator" behaviour to the cube and sets its speed. // This script could already be in the prefab. It's added here only to show that factories can be used // to fully configure any object they create. var rotator = cube.gameObject.AddComponent <Rotator>(); rotator.speed = Random.Range(0.05f, 5.0f); // Set the cube's color. cube.color = new Color(Random.Range(0, 1.0f), Random.Range(0, 1.0f), Random.Range(0, 1.0f)); // Set its position in the matrix. var transform = cube.GetComponent <Transform>(); transform.position = new Vector3(1.5f * this.currentColumn++, -1.5f * this.currentLine, 0); // Check for line break. if (this.currentColumn >= MAX_COLUMNS) { this.currentLine++; this.currentColumn = 0; } return(cube.gameObject); }
protected override void SetupContext(ref InjectionContext context) { base.SetupContext(ref context); context.Type = ContextTypes.Property; context.ContractType = provider.PropertyType; }
private void ShiftLayout(InjectionContext injectionContext) { var markerRange = injectionContext.MarkerRange; var injection = (injectionContext.Injection as TableInjection); var table = injection.Resource.Object; switch (injection.LayoutShift) { case LayoutShiftType.None: return; case LayoutShiftType.MoveRows: var countOfRowsToInsert = table.Count > 1 ? table.Count - 1 //-1 потому что одна ячейка уже есть, та в которой находиться сам маркер : 0; if (countOfRowsToInsert != 0) { injectionContext.Workbook.Worksheet(markerRange.StartMarker.Position.SheetIndex) .Row(markerRange.EndMarker.Position.RowIndex) .InsertRowsBelow(countOfRowsToInsert); } return; case LayoutShiftType.MoveCells: throw new Exception("Unsupported"); default: throw new Exception($"Unhandled case: {nameof(injection.LayoutShift)}={injection.LayoutShift.ToString()}"); } }
public void Merge(InjectionContext context, out T0 param0) { var myParams = context.Parameters; if (myParams == null || myParams.Length == 0) { _depProvider0.CreateObject(context, out param0); return; } var paramLength = myParams.Length; if (paramLength != 1) { throw ParameterNumberExceeds(context, 1, paramLength); } switch (myParams.ParameterKind) { case ParameterKind.Positional: param0 = GetPositionalDependencyObject(_depProvider0, myParams[0], context); break; case ParameterKind.Named: param0 = GetNamedDependencyObject(_depProvider0, myParams, context); break; default: throw new ImpossibleException(); } }
public override TDependency Resolve(InjectionContext context) { TDependency instance; _builder.BuildInstance(context, null, out instance); return(instance); }
public override void Execute(InjectionContext <T> context) { foreach (var activity in _activities) { activity.Execute(context); } }
public Injector(InjectionMethod injectionMethod, string processName, string dllPath, bool randomiseDllName = false) { // Ensure the users operating system is valid ValidationHandler.ValidateOperatingSystem(); // Ensure the arguments passed in are valid if (string.IsNullOrWhiteSpace(processName) || string.IsNullOrWhiteSpace(dllPath)) { throw new ArgumentException("One or more of the arguments provided were invalid"); } // Ensure a valid DLL exists at the provided path if (!File.Exists(dllPath) || Path.GetExtension(dllPath) != ".dll") { throw new ArgumentException("No DLL file exists at the provided path"); } if (randomiseDllName) { // Create a temporary DLL on disk var temporaryDllPath = DllTools.CreateTemporaryDll(DllTools.GenerateRandomDllName(), File.ReadAllBytes(dllPath)); _injectionContext = new InjectionContext(injectionMethod, processName, temporaryDllPath); } else { _injectionContext = new InjectionContext(injectionMethod, processName, dllPath); } }
protected override void SetupContext(ref InjectionContext context) { base.SetupContext(ref context); context.Type = ContextTypes.Field; context.ContractType = provider.FieldType; }
protected T DoBuildInstance(InjectionContext context, InjectionOperator <T> injectionOperator, ParameterSet parameters) { T instance; injectionOperator.DoBuildInstance(context, parameters, out instance); return(instance); }
public override void Execute(InjectionContext <DummyClass> context) { IObjectRegistration p1; ContainerOption p2; ILifetimeScope p3; _parameterMerger.Merge(context, out p1, out p2, out p3); var dummyClass = new DummyClass(p1, p2, p3); InjectInstanceIntoContext(context, dummyClass); Parameter parameter; _f0.CreateObject(context, out parameter); dummyClass.Parameter = parameter; ContainerOption option; _f1.CreateObject(context, out option); IObjectContainer container; _f2.CreateObject(context, out container); dummyClass.SetProperties(option, container); }
protected override void SetupContext(ref InjectionContext context) { base.SetupContext(ref context); context.Type |= ContextTypes.Parameter; context.ContractType = provider.ParameterType; }
public bool CanInstantiate(InjectionContext context) { SetupContext(ref context); return (GetConstructor(ref context) != null || (context.Container.Parent != null && context.Container.Parent.Instantiator.CanInstantiate(context))); }
public bool CanResolve(InjectionContext context) { SetupContext(ref context); return (GetBinding(ref context) != null || (context.Container.Parent != null && context.Container.Parent.Resolver.CanResolve(context))); }
public override void SetUp() { base.SetUp(); internalContainerMock = GetMock <IInternalContainer>(); logMock = GetMock <IGroboContainerLog>(); holderMock = null; injectionContext = new InjectionContext(internalContainerMock.Object, logMock.Object, GetHolder); }
public void TryGet_InterfaceRegistered_InstanceOfRegisteredInterface() { using (var context = new InjectionContext()) { context.Register <ITestInterface>(c => new TestClass()); Assert.IsInstanceOf <TestClass>(context.TryGet <ITestInterface>()); } }
public bool CanResolve(InjectionContext context) { SetupContext(ref context); return GetBinding(ref context) != null || (context.Container.Parent != null && context.Container.Parent.Resolver.CanResolve(context)); }
public bool CanInstantiate(InjectionContext context) { SetupContext(ref context); return GetConstructor(ref context) != null || (context.Container.Parent != null && context.Container.Parent.Instantiator.CanInstantiate(context)); }
public bool CanGet(InjectionContext context) { return (resolver.CanResolve(context) || (parent != null && parent.Resolver.CanResolve(context)) || instantiator.CanInstantiate(context) || (parent != null && parent.Instantiator.CanInstantiate(context))); }
public void RegisterAllUniqueInterfaceImplementations_MultipleInterfaceImplementations_NotRegistered() { var context = new InjectionContext(); context.RegisterAllUniqueInterfaceImplementations(true, Assembly.GetExecutingAssembly()); Assert.That(context.TryGet <IMultipleInterface>(), Is.Null); }
public static Exception RedundantParametersProvided(InjectionContext context) { var description = context.ObjectDescription; return(new ArgumentException( ExceptionFormatter.Format(context, Resources.RedundantParametersProvided, description.ConcreteType.ToFullTypeName()))); }
public override void SetUp() { base.SetUp(); internalContainer = NewMock <IInternalContainer>(); log = NewMock <IGroboContainerLog>(); holder = null; injectionContext = new InjectionContext(internalContainer, log, GetHolder); }
public void CreateContextAndFail() { var context = new InjectionContext(); //context.addMapping<string>("HELLO WORLD"); var target = new TestInjectionTarget1(); Assert.IsNullOrEmpty(target.testString); context.setMappings(target); Assert.IsNotNullOrEmpty(target.testString); }
public object GetInstance(IInjectionFactory factory, InjectionContext context) { if (!created) { instance = factory.Create(context); created = true; } return instance; }
public void Inject(InjectionContext context) { Assert.IsNotNull(context.Instance); SetupContext(ref context); var info = context.Container.Analyzer.GetAnalysis(context.Instance.GetType()); var injector = InjectorSelector.Select(context, info); injector.Inject(context, info); }
public void TestInterfaceSettingToMap() { var context = new InjectionContext(); context.addMapping<IStringProvider>(new StringProviderConcrete1()); var target = new ClassWithATestInterfaceToBeInjected(); context.setMappings(target); Assert.IsTrue(target.testStringProvider is StringProviderConcrete1); Assert.IsFalse(target.testStringProvider is StringProviderConcrete2); }
public void ConditionMeetTest() { WhenCondition condition = new WhenCondition((x, y, z) => y.GetExtraData("A") != null); InjectionContext context = new InjectionContext(null, null); Assert.False(condition.ConditionMeet(null, context, null)); context.SetExtraData("A", true); Assert.True(condition.ConditionMeet(null, context, null)); }
public void CreateContextSetString() { var context = new InjectionContext(); const string testText = "HELLO WORLD"; //context.addMapping<string>(testText); context.addMapping<String>(testText); var target = new TestInjectionTarget1(); Assert.IsNullOrEmpty(target.testString); context.setMappings(target); Assert.IsNotNullOrEmpty(target.testString); Assert.AreEqual(target.testString, testText); }
public IBinding Select(InjectionContext context, List<IBinding> bindings) { for (int i = 0; i < bindings.Count; i++) { var binding = bindings[i]; if (binding.Condition(context)) return binding; } return null; }
public IInjectableConstructor Select(InjectionContext context, IInjectableConstructor[] constructors) { for (int i = 0; i < constructors.Length; i++) { var constructor = constructors[i]; if (constructor.CanInject(context)) return constructor; } return constructors.First(); }
public IEnumerable<object> ResolveAll(InjectionContext context) { SetupContext(ref context); if (context.Container.Parent == null) return context.Container.Binder.GetBindings(context) .Select(b => b.Scope.GetInstance(b.Factory, context)); else return context.Container.Binder.GetBindings(context) .Select(b => b.Scope.GetInstance(b.Factory, context)) .Concat(context.Container.Parent.Resolver.ResolveAll(context)); }
public object Resolve(InjectionContext context) { SetupContext(ref context); var binding = GetBinding(ref context); if (binding != null) return binding.Scope.GetInstance(binding.Factory, context); // Try resolving with parent. else if (context.Container.Parent != null) return context.Container.Parent.Resolver.Resolve(context); else throw new ArgumentException(string.Format("No binding was found for context {0}.", context)); }
public void Inject(InjectionContext context, ITypeInfo info) { // Inject Fields for (int i = 0; i < info.Fields.Length; i++) info.Fields[i].Inject(context); // Inject Properties for (int i = 0; i < info.Properties.Length; i++) info.Properties[i].Inject(context); // Inject Methods for (int i = 0; i < info.Methods.Length; i++) info.Methods[i].Inject(context); }
public object Instantiate(InjectionContext context) { SetupContext(ref context); var constructor = GetConstructor(ref context); if (constructor != null) { context.Instance = constructor.Inject(context); context.Container.Injector.Inject(context); return context.Instance; } // Try instantiating with parent. else if (context.Container.Parent != null) return context.Container.Parent.Instantiator.Instantiate(context); else throw new ArgumentException(string.Format("No valid constructor was found for context {0}.", context)); }
public object Get(InjectionContext context) { if (resolver.CanResolve(context)) return resolver.Resolve(context); else if (parent != null && parent.Resolver.CanResolve(context)) return parent.Resolver.Resolve(context); else if (instantiator.CanInstantiate(context)) return instantiator.Instantiate(context); else if (parent != null && parent.Instantiator.CanInstantiate(context)) return parent.Instantiator.Instantiate(context); else return null; }
public IEnumerable<IBinding> SelectAll(InjectionContext context, List<IBinding> bindings) { return bindings.Where(b => b.Condition(context)); }
public void LocateUnknownType() { InjectionContext injectionContext = new InjectionContext(null, null); IBasicService testValue = (IBasicService)injectionContext.Locate(typeof(IBasicService)); Assert.Null(testValue); IBasicService newValue = new BasicService(); injectionContext.Export((x, y) => newValue); Assert.Null(injectionContext.Locate(typeof(ImportConstructorService))); }
public void RegisterTypeExportTest() { InjectionContext injectionContext = new InjectionContext(null, null); IBasicService testValue = (IBasicService)injectionContext.Locate(typeof(IBasicService)); Assert.Null(testValue); IBasicService newValue = new BasicService(); injectionContext.Export((x, y) => newValue); testValue = (IBasicService)injectionContext.Locate(typeof(IBasicService)); Assert.NotNull(testValue); Assert.True(ReferenceEquals(newValue, testValue)); }
public void ExtraDataTest() { InjectionContext injectionContext = new InjectionContext(null, null); Assert.Null(injectionContext.GetExtraData(TEST_VALUE_STRING)); injectionContext.SetExtraData(TEST_VALUE_STRING, NEW_VALUE); Assert.Equal(NEW_VALUE, injectionContext.GetExtraData(TEST_VALUE_STRING)); }
public bool CanGet(InjectionContext context) { return resolver.CanResolve(context) || (parent != null && parent.Resolver.CanResolve(context)) || instantiator.CanInstantiate(context) || (parent != null && parent.Instantiator.CanInstantiate(context)); }
private TransfluentLanguage currentLanguage; //put this in a view state? #endregion Fields #region Constructors public TransfluentEditorWindowMediator() { context = new InjectionContext(); context.addMapping<ICredentialProvider>(new EditorKeyCredentialProvider()); context.addMapping<IWebService>(new SyncronousEditorWebRequest()); }
public void LocateUnknownByName() { string exportName = "Test"; InjectionContext injectionContext = new InjectionContext(null, null); injectionContext.Export(exportName, (x, y) => new BasicService()); object testO = injectionContext.Locate("Test2"); Assert.Null(testO); }
public void TestNamedInjection() { var context = new InjectionContext(); const string standardKey = "HELLO WORLD"; const string namedKey = "SPECIAL STRING"; context.addMapping<string>(standardKey); context.addNamedMapping<string>(NamedInjections.INTERNAL_TESTING_SPECIAL_KEY, namedKey); var target = new TestInjectionTarget(); Assert.IsNullOrEmpty(target.testString); context.setMappings(target); Assert.AreSame(target.testString, standardKey); Assert.AreSame(target.specialString, namedKey); Assert.AreNotEqual(standardKey, namedKey); Assert.AreNotEqual(target.testString, target.specialString); }
public void LocateByName() { string exportName = "Test"; InjectionContext injectionContext = new InjectionContext(null, null); Assert.Null(injectionContext.Locate(exportName)); injectionContext.Export(exportName, (x, y) => new BasicService()); // I'm getting by to lower because exporting by name is lower case object locatedObject = injectionContext.Locate(exportName.ToLowerInvariant()); Assert.NotNull(locatedObject); }
private static bool LocateExportByType(IExportLocator locator, ExportStrategyDependency exportStrategyDependency) { if (locator.GetStrategy(exportStrategyDependency.ImportType) != null) { return true; } if (TestForSpecialType(locator, exportStrategyDependency.ImportType)) { return true; } if (exportStrategyDependency.ImportType.GetTypeInfo().IsClass && !exportStrategyDependency.ImportType.GetTypeInfo().IsAbstract && !exportStrategyDependency.ImportType.GetTypeInfo().IsInterface) { return true; } IInjectionScope injectionScope = locator as IInjectionScope; if (injectionScope != null) { InjectionContext context = new InjectionContext(injectionScope); foreach (ISecondaryExportLocator secondaryExportLocator in injectionScope.SecondaryExportLocators) { if (secondaryExportLocator.CanLocate(context, null, exportStrategyDependency.ImportType, null, null)) { return true; } } if (injectionScope.ParentScope != null) { return LocateExportByType(injectionScope.ParentScope, exportStrategyDependency); } } return false; }
public IMemberInjector Select(InjectionContext context, ITypeInfo info) { return injector; }
public void ImportDateTime() { DependencyInjectionContainer container = new DependencyInjectionContainer(); container.Configure(c => c.Export<ImportDateTimeByName>()); InjectionContext context = new InjectionContext(container.RootScope) { { "DateTime", (x, y) => DateTime.Now } }; ImportDateTimeByName importName = container.Locate<ImportDateTimeByName>(injectionContext: context); Assert.NotNull(importName); Assert.Equal(DateTime.Today, importName.DateTime.Date); }
public void InjectionContextResolveTest() { DependencyInjectionContainer container = new DependencyInjectionContainer(); container.Configure(c => c.Export<BasicService>().As<IBasicService>()); InjectionContext context = new InjectionContext(container.RootScope) { { "stringParam", "Hello" }, { "intParam", (x, y) => 7 } }; WithCtorParamClass paramClass = container.Locate<WithCtorParamClass>(injectionContext: context); Assert.NotNull(paramClass); Assert.Equal("Hello", paramClass.StringParam); Assert.Equal(7, paramClass.IntParam); }