简体   繁体   中英

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 ). I'm getting error when I'm trying to inject any BLL service as Dependancy in my Controller . I have implemented the following 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):

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:

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:

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. You need to register them manually in the ConfigureServices method which is in Startup.cs , for example:

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:

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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