Carl Rippon
Carl Rippon

Reputation: 4673

ASP.NET5 Dependency Injection into a none controller class

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: enter image description here

I'm sure I'm missing something silly - any help would be appreciated!

Upvotes: 0

Views: 367

Answers (1)

agua from mars
agua from mars

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

Related Questions