Skip to content

Dependency Injection

Matthias Beerens edited this page Aug 9, 2019 · 5 revisions

Use a DI/IoC container

To use a custom DI/IoC container you will need to create a custom resolver. This resolver will pass the work on to the underlying DI/IoC container.

using MatthiWare.CommandLine.Abstractions;

public class CustomResolver : IContainerResolver
{
    /// IContainer respresents an 3rd party DI Container type.  
    private readonly IContainer _container;

    public CustomResolver(IContainer container)
    {
        _container = container;
    }

    public T Resolve<T>()
    {
        // Resolve the type using a given 3rd party DI Container.
        return _container.Resolve<T>();
    }
}

Now you can use it as following

public static void Main(string[] args)
{
    // Pass the custom resolver using the constructor into the parser
    var parser = new CommandLineParser<OptionModel>(new CustomResolver(new SomeDIContainer()));

    // Use the parser as normal.. 
    var result = parser.Parse(args);
}
Clone this wiki locally