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

时间:2018-02-12 17:22:18

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

我有使用asp.net core 2.0 Web ApiBLL)的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();
    }
}

buildsuccessful,但当我调用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'.

有什么想法吗?

2 个答案:

答案 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)。