Skip to content

DependencyProvider

Lunar Doggo edited this page Apr 17, 2022 · 2 revisions

What is it?

IDependencyProvider provides a common interface for injecting dependencies into constructor parameters of IApplicationCommands that aren't decorated with a StartOptionAttribute.

Implementation

public interface IDependencyProvider

Methods

Signature Description
public object GetDependency(Type type) Returns the dependency of the provided type
public T GetDependency<T>() Returns the dependency of the provided generic type

SimpleDependencyProvider

The library already ships with the implementation for you to use, called SimpleDependencyProvider. The implementation is quite basic, only allowing you to register already existing instances of dependencies. If you wish to use a dependency injection framework, set the framework up as usual and create a custom implementation of IDependencyProvider that acts as a proxy between the framework and this library.

SimpleDependencyProvider is implemented like so:

public class SimpleDependencyProvider : IDependencyProvider
{
  //If you want an exception to be thrown in the case that a dependency can't be resolved, use throwExceptionIfDependencyNotFound = true
  public SimpleDependencyProvider(bool throwExceptionIfDependencyNotFound) {...}
  //Add dependencies to the cache with this method; each type <T> can only be registered once!
  public void AddSingleton<T>(T value) {...}

  public T GetDependency<T>() {...}
  public object GetDependency(Type type) {...}

}

Example

SimpleDependencyProvider provider = new SimpleDependencyProvider(false); //don't throw an exception if a dependency can't be resolved
//Add your dependencies like so
provider.AddSingleton<IDatabase>(new MockDatabase());
provider.AddSingleton(IPAddress.Loopback);
provider.AddSingleton("value");