Reputation: 4673
I'm struggling to get dependency injection working in a none controller class in ASP.NET 5.
I'm trying to inject an instance of IHelloMessage in ResponseWriter.
I have the following code in startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<IHelloMessage, HelloMessage>();
}
public void Configure(IApplicationBuilder app)
{
app.Run(async context =>
{
await Task.Run(() =>
{
new ResponseWriter().Write(context);
});
});
}
I have the following code in ResponseWriter.cs:
public class ResponseWriter
{
public IHelloMessage HelloMessage { get; set; }
public ResponseWriter()
{
}
public ResponseWriter(IHelloMessage helloMessage)
{
HelloMessage = helloMessage;
}
public void Write(HttpContext HttpContext)
{
HttpContext.Response.WriteAsync(HelloMessage.Text);
}
}
and here's the code for HelloMessage:
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();
}
}
When I run the app, I get the following error:
I'm sure I'm missing something silly - any help would be appreciated!
Upvotes: 0
Views: 367
Reputation: 17424
You are calling your parameter less constructor: new ResponseWriter().Write(context);
so your HelloMessage is null.
If you want to use dependency injection you must use IAppBuilder.ApplicationService.GetService
or IAppBuilder.ApplicationService.GetRequiredService
methods
Your statup.cs can be:
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<IHelloMessage, HelloMessage>();
}
public void Configure(IApplicationBuilder app)
{
app.Run(async context =>
{
await Task.Run(() =>
{
new ResponseWriter(app.ApplicationServices.GetRequiredService<IHelloMessage>()).Write(context);
});
});
}
Upvotes: 1