Asp 核心网络 api 控制器在注入服务时不工作

Asp core web api controller not working when injecting service

我是 ASP.NET Core 的新手。想要使用这个新框架创建一个 api,但是依赖注入有一些启动问题。这应该很容易,但是不知何故,当使用 DI 时,我在从邮递员调用控制器时收到内部服务器错误 500。

控制器:

[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";
    }
}

接口服务

public interface ISomethingService
{
    int status();
}

public class SomethingService : ISomethingService
{
    SomethingService()
    {
    }

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

启动class

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

如您所见,我已经注册了该服务,为什么它没有按预期运行?

另外,试过从控制器上取下注射器,然后控制器工作正常。

您的 SomethingService 构造函数是 private。让它 public 这样 DI 就可以创建一个。