我有使用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();
}
}
}
我已在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
为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'.
有什么想法吗?
答案 0 :(得分:4)
默认情况下,DI容器不了解您的服务。您需要在ConfigureServices
中的Startup.cs
方法中手动注册它们,例如:
public void ConfigureServices(IServiceCollection services)
{
//Snip
services.AddScoped<ITestService, TestService>();
}
请参阅the docs以了解服务所需的生命周期(即范围,单身或瞬态)
答案 1 :(得分:2)
在Startup类中,您需要手动将所需的每个服务添加到DI容器中:
public void ConfigureServices(IServiceCollection services)
{
// your current code goes here
// ...
services.AddScoped<ITestService, TestService>();
}
如果您希望自动执行此操作,则需要添加更专业的容器(如Autofac或StructureMap)。