Csharp provider injection

Dependency injection is awesome, but not always I want to be all in. Sometimes I want to be able instantiate an object without adding it in a bootstrap. But at the same time I don’t want to use keyword new. To make it more fun, I want to inject objects from service provider into newly instantiated Object.

Google solved this in Java with some Guice. An object capable of providing instances of type T. I miss this in csharp and I want it.

So I created it

Simple interface

1
2
3
4
5
6
public interface IProvider<out T>
{
    T Get();

    T Get(params object[] parameters);
}

Very simple implementation because of “ActivatorUtilities” helper. It does the all heavy lifting and locates all the missing parts inside a service provider to create the object, if needed.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Provider<T> : IProvider<T>
{
    private readonly IServiceProvider _serviceProvider;

    public Provider(IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider;
    }

    public T Get()
    {
        return ActivatorUtilities.CreateInstance<T>(_serviceProvider);
    }

    public T Get(params object[] parameters)
    {
        return ActivatorUtilities.CreateInstance<T>(_serviceProvider, parameters);
    }
}

Add Provider injection in Startup.cs

1
2
3
4
5
6
public void ConfigureServices(IServiceCollection services)
{
    // ****
    services.AddProviderInjection();
    // ****
}

And get ready to rock the solution with some powerful stuff.

inject

1
2
3
4
public ValuesController(IProvider<ValueService> provider)
{
    _provider = provider;
}

use

1
2
3
4
5
[HttpGet]
public IEnumerable<string> Get()
{
    return _provider.Get().GetValues();
}

Add custom in injection

1
2
3
4
5
6
[HttpGet("admin")]
public IEnumerable<string> GetAdmin()
{
    const string connectionString = "connectToAdminDB";
    return _provider.Get(connectionString).GetValues();
}

Code and example in GitHub

Install it as package

1
Install-Package Provider -Version 1.0.2

Leave a Reply

Your email address will not be published. Required fields are marked *