繁体   English   中英

在asp.net core 2.0中使用DI来注入BLL服务

[英]Use DI in asp.net core 2.0 for injecting BLL services

我有使用BLLBusiness Logic Layer )的asp.net core 2.0 Web Api项目。 当我尝试在Controller注入任何BLL服务作为Dependancy时,我收到错误。 我已经实现了以下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但是当我调用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>();
}

查看文档以了解服务所需的生命周期(即作用域,单例或瞬态)

在Startup类中,您需要手动将所需的每个服务添加到DI容器中:

public void ConfigureServices(IServiceCollection services)
{
    // your current code goes here
    // ...

    services.AddScoped<ITestService, TestService>();
}

如果您希望自动执行此操作,则需要添加更专业的容器(如Autofac或StructureMap)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM