user1097128
user1097128

Reputation: 113

How to use dependency injection in web api controller class for dbset objects

I am use DI in my controller class as documented here. The object I am passing with DI has to be used as dbset.

public class ValuesController : ControllerBase
{
    private readonly RPContext _context;
    private IResource _resource;

    public ValuesController(RPContext context, IResource resource)
    {
        _context = context;
        _resource = resource;
    }

    [HttpPost("{id}/{resourceName}")]
    public void Post([FromRoute] string id, [FromRoute] string resourceName, [FromBody] JObject Request)
    {
        _resource.Id = id;
        _resource.Name = resourceName;
        _resource.Location = (string)Request["location"];
        _context.Resources.Add(_resource);
        _context.SaveChangesAsync();
    }

I cannot use "_resource" in the above code with the Add method of Dbcontext object because it is an interface and not of class type. How else should I be doing this if I don't want to create new objects in my controller class?

Upvotes: 1

Views: 347

Answers (1)

user4864425
user4864425

Reputation:

Please note that IResource is the interface of a service, not an object itself. So IResource isn't a new object. If you need a new object you can take a factory approach:

var resource = _resource.Create();

To add an entity to the context:

[HttpPost("{resourceName}")]
public async Task<IActionResult> Post([FromRoute]string resourceName, [FromBody]JObject Request)
{
    var resource = new Data.Entities.Resource
    {
        Name = resourceName,
        Location = (string)Request["location"]
    };
    _context.Resources.Add(resource);
    _context.SaveChangesAsync();

     return CreatedAtRoute("Get", new { id = resource.Id }, resource.Id);
}

Where the result links to the created object.

I noticed that you've included an Id for this request. But it seems that a new resource is created, so I've omitted the Id because it is probably set in the database.

Upvotes: 1

Related Questions