Skip to content

Commit

Permalink
feat(DependencyInjector): add constructor for constructing injector u…
Browse files Browse the repository at this point in the history
…sing DependencyAttributes
  • Loading branch information
jonisavo committed May 1, 2022
1 parent 9583b39 commit 7b697b7
Showing 1 changed file with 16 additions and 17 deletions.
33 changes: 16 additions & 17 deletions Core/DependencyInjector.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
using System.Collections.Generic;
using JetBrains.Annotations;
using UIComponents.Core.Exceptions;
using UnityEngine;

namespace UIComponents.Core
{
Expand Down Expand Up @@ -36,13 +35,11 @@ public static DependencyInjector GetInjector(Type consumerType)

private static DependencyInjector CreateInjector(Type consumerType)
{
var injector = new DependencyInjector();

var injectAttributes = (DependencyAttribute[])
consumerType.GetCustomAttributes(typeof(DependencyAttribute), true);

injector.PopulateFromDependencyAttributes(injectAttributes);
var injector = new DependencyInjector(injectAttributes);

InjectorDictionary.Add(consumerType, injector);

return injector;
Expand All @@ -64,6 +61,20 @@ private static object CreateInstance(Type dependencyType)

return instance;
}

public DependencyInjector() {}

public DependencyInjector(IEnumerable<DependencyAttribute> dependencyAttributes)
{
foreach (var dependencyAttribute in dependencyAttributes)
{
var type = dependencyAttribute.DependencyType;
var providerType = dependencyAttribute.ProvideType;

if (!DependencyDictionary.ContainsKey(type))
DependencyDictionary[type] = CreateInstance(providerType);
}
}

public void SetDependency<T>([NotNull] T instance) where T : class
{
Expand Down Expand Up @@ -96,17 +107,5 @@ private static object CreateInstance(Type dependencyType)

return true;
}

private void PopulateFromDependencyAttributes(IEnumerable<DependencyAttribute> dependencyAttributes)
{
foreach (var dependencyAttribute in dependencyAttributes)
{
var type = dependencyAttribute.DependencyType;
var providerType = dependencyAttribute.ProvideType;

if (!DependencyDictionary.ContainsKey(type))
DependencyDictionary[type] = CreateInstance(providerType);
}
}
}
}

0 comments on commit 7b697b7

Please sign in to comment.