2015-04-21 65 views
0

我努力讓依賴注入的無控制器類工作在ASP.NET 5.ASP.NET5依賴注入到無控制器類

我試圖注入的實例IHelloMessageResponseWriter

我在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); 
     }); 
    }); 
} 

我在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); 
    } 
} 

,這裏是爲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(); 
    } 
} 

當我運行應用程序,我得到以下錯誤: enter image description here

我敢肯定,我失去了一些愚蠢的 - 任何幫助,將不勝感激!

+1

是HttpContext的空? – jfin3204

回答

1

你正在調用你的參數少構造函數:new ResponseWriter().Write(context);所以你的HelloMessage爲null。
如果你想使用依賴注入,你必須使用IAppBuilder.ApplicationService.GetServiceIAppBuilder.ApplicationService.GetRequiredService方法

statup.cs可以是:

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); 
     }); 
    }); 
}