ASP.NET Core now has a built in default DI container. Here’s a simple example of using this that isn’t in a Controller class (all the examples I’ve seen so far are how to inject objects into a controller) …

Mapping our interfaces

First we need to map our interfaces to the implementations we want the app to use in Startup.ConfigureServices()

public void ConfigureServices(IServiceCollection services)
{
    services.AddTransient<IHelloMessage, HelloMessage>();
}

This code tells the DI container that when IHelloMessage is requested, return a new instance of HelloMessage.

The code for IHelloMessage and HelloMessage is below:

public interface IHelloMessage
{
    string Text { get; set; }
}

public class HelloMessage : IHelloMessage
{
    public string Text { get; set; }

    public HelloMessage()
    {
        Text = "Hello world at " + DateTime.Now.ToString();
    }
}

Requesting the implementation

Controller classes do this for us but we use IApplicationBuilder.ApplicationServices.GetRequiredService() to get the implementation for other classes.

The code below injects IHelloMessage into ResponseWriter during each http request.

public void Configure(IApplicationBuilder app)
{
    app.Run(async context =>
    {
        await Task.Run(() =>
        {
            new ResponseWriter(app.ApplicationServices.GetRequiredService<IHelloMessage>()).Write(context);
        });
    });
}

#asp.net #dependency

ASP.NET Core Dependency Injection
1.10 GEEK