Skip to content

Commit

Permalink
feat(DependencyInjector): add TryProvide method
Browse files Browse the repository at this point in the history
  • Loading branch information
jonisavo committed May 1, 2022
1 parent 4ccebe5 commit 9583b39
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 18 deletions.
13 changes: 13 additions & 0 deletions Core/DependencyInjector.cs
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,19 @@ public T Provide<T>() where T : class

return (T) DependencyDictionary[type];
}

public bool TryProvide<T>(out T instance) where T : class
{
instance = null;
var type = typeof(T);

if (!DependencyDictionary.ContainsKey(type))
return false;

instance = (T) DependencyDictionary[type];

return true;
}

private void PopulateFromDependencyAttributes(IEnumerable<DependencyAttribute> dependencyAttributes)
{
Expand Down
33 changes: 32 additions & 1 deletion Tests/DependencyInjectorTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,40 @@ public void Throws_If_No_Provider_Exists()
{
var injector = new DependencyInjector();

Assert.Throws<MissingProviderException>(
var exception = Assert.Throws<MissingProviderException>(
() => injector.Provide<IDependency>()
);

Assert.That(exception.Message, Is.EqualTo("No provider found for IDependency"));
}
}

[TestFixture]
public class TryProvide
{
[Test]
public void Returns_If_Dependency_Could_Be_Provided()
{
var injector = new DependencyInjector();

Assert.That(injector.TryProvide<IDependency>(out _), Is.False);

injector.SetDependency<IDependency>(new DependencyOne());

var wasProvided = injector.TryProvide<IDependency>(out var instance);

Assert.That(wasProvided, Is.True);
Assert.That(instance, Is.InstanceOf<DependencyOne>());
}

[Test]
public void Yields_Null_If_Dependency_Can_Not_Be_Provided()
{
var injector = new DependencyInjector();

injector.TryProvide<IDependency>(out var instance);

Assert.That(instance, Is.Null);
}
}

Expand Down
17 changes: 0 additions & 17 deletions Tests/UIComponentDependencyTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,16 +49,6 @@ public UIComponentSubclassWithDependencyOverride()
}
}

private class UIComponentWithNoProvider : UIComponent
{
public readonly IStringDependency StringDependency;

public UIComponentWithNoProvider()
{
StringDependency = Provide<IStringDependency>();
}
}

[Test]
public void The_Correct_Class_Is_Provided_To_Component()
{
Expand All @@ -72,12 +62,5 @@ public void The_Correct_Class_Is_Provided_To_Component_When_Overridden()
var component = new UIComponentSubclassWithDependencyOverride();
Assert.That(component.StringDependency, Is.InstanceOf<EmptyStringProvider>());
}

[Test]
public void Null_Is_Provided_When_No_Provider_Exists()
{
var component = new UIComponentWithNoProvider();
Assert.That(component.StringDependency, Is.Null);
}
}
}

0 comments on commit 9583b39

Please sign in to comment.