Ark*_*adi 3 c# asp.net dependency-injection .net-core asp.net-core-2.0
我有asp.net core 2.0 Web Api使用BLL( Business Logic Layer) 的项目。当我尝试BLL像Dependancy在我的Controller. 我已经实现了以下内容Controller:
namespace MyProject.WebApi.Controllers
{
[Route("api/test")]
public class TestController : Controller
{
private readonly ITestService _testService;
public TestController(ITestService testService)
{
_testService = testService;
}
[HttpGet, Route("get-all")]
public List<Test> Get()
{
return _testService.GetTestList();
}
}
}
Run Code Online (Sandbox Code Playgroud)
我已经在BLL(单独的项目)中实现了测试服务:
namespace MyProject.Core
{
public class TestService : ITestService
{
private readonly ITestEngine _testEngine;
public TestService(ITestEngine testEngine)
{
_testEngine = testEngine;
}
public List<Test> GetTestList()
{
return _testEngine.GetTestList();
}
}
}
Run Code Online (Sandbox Code Playgroud)
我的界面TestService如下所示:
namespace MyProject.Core
{
public interface ITestService
{
List<Test> GetTestList();
}
}
Run Code Online (Sandbox Code Playgroud)
的build是successful,但是当我打电话Get的方法TestController,我发现了以下错误:
fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[0]
An unhandled exception has occurred while executing the request
System.InvalidOperationException: Unable to resolve service for type 'MyProject.Infrastructure.Interface.ITestEngine' while attempting to activate 'MyProject.Core.TestService'.
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
默认情况下,DI 容器不知道您的服务。您需要在 中的ConfigureServices方法中手动注册它们Startup.cs,例如:
public void ConfigureServices(IServiceCollection services)
{
//Snip
services.AddScoped<ITestService, TestService>();
}
Run Code Online (Sandbox Code Playgroud)
请参阅文档以了解服务所需的生命周期(即范围、单例或瞬态)