2017-02-18 15 views
-1

私はASP.NET Coreを初めて使用しています。この新しいフレームワークを使用してAPIを作成したいが、依存性注入に関するいくつかの起動上の問題がある。それは非常に簡単ですが、何とかDIを使用すると、郵便配達員からコントローラを呼び出すときに内部サーバエラー500が発生します。サービスの注入時にAspコアWeb APIコントローラが動作しない

コントローラー:インタフェース

public interface ISomethingService 
{ 
    int status(); 
} 

public class SomethingService : ISomethingService 
{ 
    SomethingService() 
    { 
    } 

    public int status() 
    { 
     var number = 3; 
     return number; 
    } 
} 

起動クラス

public class Startup 
{ 
    public Startup(IHostingEnvironment env) 
    { 
     var builder = new ConfigurationBuilder() 
      .SetBasePath(env.ContentRootPath) 
      .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) 
      .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) 
      .AddEnvironmentVariables(); 
     Configuration = builder.Build(); 
    } 

    public IConfigurationRoot Configuration { get; } 

    // This method gets called by the runtime. Use this method to add services to the container. 
    public void ConfigureServices(IServiceCollection services) 
    { 
     // Add framework services. 
     services.AddMvc(); 

     // Add application services 
     services.AddTransient<ISomethingService, SomethingService>(); 
    } 

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 
    { 
     loggerFactory.AddConsole(Configuration.GetSection("Logging")); 
     loggerFactory.AddDebug(); 

     app.UseMvc(); 
    } 
} 

として有する

[Route("api/[controller]")] 
public class SomethingController : Controller 
{ 
    private readonly ISomethingService _somethingService; 

    public SomethingController(ISomethingService somethingService) 
    { 
     _somethingService = somethingService; 
    } 

    // GET: api/values 
    [HttpGet] 
    public int Get() 
    { 
     return _somethingService.status(); 
    } 

    // GET api/values/5 
    [HttpGet("{id}")] 
    public string Get(int id) 
    { 
     return "value"; 
    } 
} 

サービスあなたは、私はすでにサービスを登録しているので、それは意図したとおりに動作しないのはなぜですか?

また、コントローラからインジェクタンを取り外そうとしましたが、コントローラが正常に動作しています。

+0

多分、ConigurationServicesのサービスの前にaddign mvc? – miechooy

+0

私はそれをScoped Not Transientとして登録し、services.AddMvcへの呼び出しの前に登録します。問題ありません。 –

+0

service.AddMVCを呼び出しても問題はありません。 service.AddScoped <> – Mikkel

答えて

2

SomethingServiceコンストラクタはprivateです。 DIを作成できるようにpublicにしてください。

+0

この種のエラーは時々実際には厄介なものです。あなたに良い一日をお過ごしください。うまくいきました。 – Mikkel

+0

このコンストラクタを削除するだけです。 –

関連する問題