我有 asp.net core 2.0 Web Api
项目,它使用 BLL
(业务逻辑层
)。当我尝试将任何 BLL
服务作为 Dependancy
注入(inject)到我的 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();
}
}
}
我在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();
}
}
}
TestService
的界面如下所示:
namespace MyProject.Core
{
public interface ITestService
{
List<Test> GetTestList();
}
}
build
成功
但是当我调用 TestController
的 Get
方法时出现以下错误:
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'.
有什么想法吗?
最佳答案
默认情况下,DI 容器不知道您的服务。您需要在 Startup.cs
中的 ConfigureServices
方法中手动注册它们,例如:
public void ConfigureServices(IServiceCollection services)
{
//Snip
services.AddScoped<ITestService, TestService>();
}
参见 the docs了解服务所需的生命周期(即作用域、单例或 transient )
关于c# - asp.net core 2.0中使用DI注入(inject)BLL服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48752071/