[英]Use DI in asp.net core 2.0 for injecting BLL services
I have asp.net core 2.0 Web Api
project that uses BLL
( Business Logic Layer
). 我有使用
BLL
( Business Logic Layer
)的asp.net core 2.0 Web Api
项目。 I'm getting error when I'm trying to inject any BLL
service as Dependancy
in my Controller
. 当我尝试在
Controller
注入任何BLL
服务作为Dependancy
时,我收到错误。 I have implemented the following 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();
}
}
}
I have implemented test service in BLL
(separate project): 我在
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();
}
}
}
And my interface for TestService
looks like this: 我的
TestService
接口如下所示:
namespace MyProject.Core
{
public interface ITestService
{
List<Test> GetTestList();
}
}
The build
is successful
but when I call Get
method of TestController
I'm getting the following error: build
successful
但是当我调用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'.
Any ideas? 有任何想法吗?
By default, the DI container doesn't know about your services. 默认情况下,DI容器不知道您的服务。 You need to register them manually in the
ConfigureServices
method which is in Startup.cs
, for example: 您需要在
Startup.cs
中的ConfigureServices
方法中手动注册它们,例如:
public void ConfigureServices(IServiceCollection services)
{
//Snip
services.AddScoped<ITestService, TestService>();
}
See the docs to understand the lifetime you need for the service (ie scoped, singleton or transient) 查看文档以了解服务所需的生命周期(即作用域,单例或瞬态)
In the Startup class, you need to manually add each service you want into the DI container: 在Startup类中,您需要手动将所需的每个服务添加到DI容器中:
public void ConfigureServices(IServiceCollection services)
{
// your current code goes here
// ...
services.AddScoped<ITestService, TestService>();
}
If you want this to happen automatically, you will need to add a more specialized container (like Autofac or StructureMap). 如果您希望自动执行此操作,则需要添加更专业的容器(如Autofac或StructureMap)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.