Reputation: 305
I'm moving the data access portion of a project to a WebAPI and using Entity Framework Core to do what EF does.
I know that the preferred pattern is to now rely on dependency injection to create the dbContext when "the controller" is used. The "Hello, World!" tutorials show examples of accessing the context by the following:
private BloggingContext _context;
public BlogsController(BloggingContext context)
{
_context = context;
}
The issue that I'm having is I need to go one layer up...as I have a "Service" interface that exposes the methods of the repository.
I tried putting the context instantiation into my repository, but, of course, then when I tried to new up an instance of the service, it was requiring a context object to be passed in. I tried to resolve it by sending in a new BloggingContext() as the context parameter, but received the error: No database provider has been configured for this DbContext.
Which, of course, makes sense because the new
one that I was passing in didn't have a connection to the database associated with it. That connection is defined in the Startup.cs as described in the various tutorials I'm following trying to cut my teeth on this transition.
So, given the following code in my controller, how can I invoke the service and still let the Dependency Injection do what it's designed to do at the repository level?
[HttpGet("{bool}")]
public IActionResult GetRoleNames(bool? isActive)
{
var service = new SecurityService();
try
{
return Ok(service.GetRoleNames(isActive));
}
catch (Exception ex)
{
Log.Error("Failed to get list of role names from the API", ex.Message);
return BadRequest(ex);
}
}
I'm pretty sure I have the [HttpGet("{bool}")]
a bit FUBARd as well since GetRoleNames
will permit NULL, but I'll cross that bridge after resolving the DI issue.
Upvotes: 2
Views: 897
Reputation: 798
Use Dependency Injection to create your service (I like to have an interface)-
private readonly ISecurityService _service;
public BlogsController(ISecurityService service)
{
_service = service;
}
Call your method using the constructed service
[HttpGet("{bool}")]
public IActionResult GetRoleNames(bool? isActive)
{
try
{
return Ok(_service.GetRoleNames(isActive));
}
catch (Exception ex)
{
Log.Error("Failed to get list of role names from the API", ex.Message);
return BadRequest(ex);
}
}
Your security service can have the context injected
private readonly BloggingContext _context;
public class SecurityService : ISecurityService
{
public SecurityService (BloggingContext context)
{
_context = context
}
}
You can register your service in Startup.cs in the ConfigureServices method:
service.AddScoped<ISecurityService, SercurityService>();
Upvotes: 3