Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 410
Arkadi Avatar asked Oct 30 '25 01:10

Arkadi


2 Answers

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 (i.e. scoped, singleton or transient)

like image 124
DavidG Avatar answered Nov 01 '25 17:11

DavidG


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

like image 41
Camilo Terevinto Avatar answered Nov 01 '25 16:11

Camilo Terevinto