c# - asp.net core 2.0中使用DI注入(inject)BLL服务

标签 c# asp.net dependency-injection .net-core asp.net-core-2.0

我有 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 成功 但是当我调用 TestControllerGet 方法时出现以下错误:

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/

相关文章:

asp.net - View 状态和 session 哪个成本更高?

c# - 使用 WebBrowser Winforms 控件通过 SSL 访问内网

c# - 如何使用 Tridion 的出站电子邮件 API 检索联系人的关键字?

c# - 并发字典 AddOrUpdate 与索引添加

c# - 找不到 ASP.NET 母版页

java - 如何正确地进行依赖注入(inject)(在 Spring 中)?

c# - 将授权 header 添加到 Web 引用

c# - ASP.NET Repeater - Eval() for bool?

android - 如何使用 koin 注入(inject) View 模型? (针对特定用例)

c# - ASP.Net-Core 选项验证