ASP.NET Core Dependency Injection
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); }); });}
The code for ResponseWriter is below:
public class ResponseWriter{ public IHelloMessage HelloMessage { get; set; }
public ResponseWriter(IHelloMessage helloMessage) { HelloMessage = helloMessage; } public void Write(HttpContext HttpContext) { HttpContext.Response.WriteAsync(HelloMessage.Text); }}
If we run the app, we get something like below and everytime you refresh the browser, the time within the message should change.
Other mapping options
If we wanted to only use a single instance when IHelloMessage is requested, we could have used:
public void ConfigureServices(IServiceCollection services){ services.AddScoped<IHelloMessage, HelloMessage>();}
Now when we refresh the browser, the time should stay static.
If we wanted a specific instance to be used, we could have used:
public void ConfigureServices(IServiceCollection services){ services.AddInstance<IHelloMessage>(new HelloMessage() {Text="My instance"});}
Now when the run the app, we should see “My instance” in the web page.