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











up vote
1
down vote

favorite












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?










share|improve this question
























  • This question contains a LOT of things: 1. The controller inherit to ControllerBase instead of Controller. 2. Using asynchronous task but returning void. 3. Try to cast an interface to a class... I suggest you to read the documentation careful and follow step-by-step to understand how it works. Or just download the project and run (via the link you provide).
    – Foo
    Nov 10 at 7:34










  • async was a copy-paste mistake made while adding code here from older version, removed it. When you create web api project through Visual Studio, it only inerits from controllerbase. Seems like Controller is for MVC views and models which I don't need.
    – user1097128
    Nov 10 at 9:53










  • @TânNguyễn About ControllerBase: docs.microsoft.com/nl-nl/aspnet/core/web-api/…
    – Ruard van Elburg
    Nov 10 at 14:04












  • @RuardvanElburg Indeed, we can use almost everything in Web API with a class that inherits from Controller, not just ControllerBase (I'm sure). And the question about the difference(s) may be in another post. I said that because: when I create new controller in my project (.net core 2.1), it inherits from Controller.
    – Foo
    Nov 10 at 14:45

















up vote
1
down vote

favorite












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?










share|improve this question
























  • This question contains a LOT of things: 1. The controller inherit to ControllerBase instead of Controller. 2. Using asynchronous task but returning void. 3. Try to cast an interface to a class... I suggest you to read the documentation careful and follow step-by-step to understand how it works. Or just download the project and run (via the link you provide).
    – Foo
    Nov 10 at 7:34










  • async was a copy-paste mistake made while adding code here from older version, removed it. When you create web api project through Visual Studio, it only inerits from controllerbase. Seems like Controller is for MVC views and models which I don't need.
    – user1097128
    Nov 10 at 9:53










  • @TânNguyễn About ControllerBase: docs.microsoft.com/nl-nl/aspnet/core/web-api/…
    – Ruard van Elburg
    Nov 10 at 14:04












  • @RuardvanElburg Indeed, we can use almost everything in Web API with a class that inherits from Controller, not just ControllerBase (I'm sure). And the question about the difference(s) may be in another post. I said that because: when I create new controller in my project (.net core 2.1), it inherits from Controller.
    – Foo
    Nov 10 at 14:45















up vote
1
down vote

favorite









up vote
1
down vote

favorite











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?










share|improve this question















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?







entity-framework asp.net-core dependency-injection entity-framework-core






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 10 at 9:48

























asked Nov 10 at 5:03









user1097128

289




289












  • This question contains a LOT of things: 1. The controller inherit to ControllerBase instead of Controller. 2. Using asynchronous task but returning void. 3. Try to cast an interface to a class... I suggest you to read the documentation careful and follow step-by-step to understand how it works. Or just download the project and run (via the link you provide).
    – Foo
    Nov 10 at 7:34










  • async was a copy-paste mistake made while adding code here from older version, removed it. When you create web api project through Visual Studio, it only inerits from controllerbase. Seems like Controller is for MVC views and models which I don't need.
    – user1097128
    Nov 10 at 9:53










  • @TânNguyễn About ControllerBase: docs.microsoft.com/nl-nl/aspnet/core/web-api/…
    – Ruard van Elburg
    Nov 10 at 14:04












  • @RuardvanElburg Indeed, we can use almost everything in Web API with a class that inherits from Controller, not just ControllerBase (I'm sure). And the question about the difference(s) may be in another post. I said that because: when I create new controller in my project (.net core 2.1), it inherits from Controller.
    – Foo
    Nov 10 at 14:45




















  • This question contains a LOT of things: 1. The controller inherit to ControllerBase instead of Controller. 2. Using asynchronous task but returning void. 3. Try to cast an interface to a class... I suggest you to read the documentation careful and follow step-by-step to understand how it works. Or just download the project and run (via the link you provide).
    – Foo
    Nov 10 at 7:34










  • async was a copy-paste mistake made while adding code here from older version, removed it. When you create web api project through Visual Studio, it only inerits from controllerbase. Seems like Controller is for MVC views and models which I don't need.
    – user1097128
    Nov 10 at 9:53










  • @TânNguyễn About ControllerBase: docs.microsoft.com/nl-nl/aspnet/core/web-api/…
    – Ruard van Elburg
    Nov 10 at 14:04












  • @RuardvanElburg Indeed, we can use almost everything in Web API with a class that inherits from Controller, not just ControllerBase (I'm sure). And the question about the difference(s) may be in another post. I said that because: when I create new controller in my project (.net core 2.1), it inherits from Controller.
    – Foo
    Nov 10 at 14:45


















This question contains a LOT of things: 1. The controller inherit to ControllerBase instead of Controller. 2. Using asynchronous task but returning void. 3. Try to cast an interface to a class... I suggest you to read the documentation careful and follow step-by-step to understand how it works. Or just download the project and run (via the link you provide).
– Foo
Nov 10 at 7:34




This question contains a LOT of things: 1. The controller inherit to ControllerBase instead of Controller. 2. Using asynchronous task but returning void. 3. Try to cast an interface to a class... I suggest you to read the documentation careful and follow step-by-step to understand how it works. Or just download the project and run (via the link you provide).
– Foo
Nov 10 at 7:34












async was a copy-paste mistake made while adding code here from older version, removed it. When you create web api project through Visual Studio, it only inerits from controllerbase. Seems like Controller is for MVC views and models which I don't need.
– user1097128
Nov 10 at 9:53




async was a copy-paste mistake made while adding code here from older version, removed it. When you create web api project through Visual Studio, it only inerits from controllerbase. Seems like Controller is for MVC views and models which I don't need.
– user1097128
Nov 10 at 9:53












@TânNguyễn About ControllerBase: docs.microsoft.com/nl-nl/aspnet/core/web-api/…
– Ruard van Elburg
Nov 10 at 14:04






@TânNguyễn About ControllerBase: docs.microsoft.com/nl-nl/aspnet/core/web-api/…
– Ruard van Elburg
Nov 10 at 14:04














@RuardvanElburg Indeed, we can use almost everything in Web API with a class that inherits from Controller, not just ControllerBase (I'm sure). And the question about the difference(s) may be in another post. I said that because: when I create new controller in my project (.net core 2.1), it inherits from Controller.
– Foo
Nov 10 at 14:45






@RuardvanElburg Indeed, we can use almost everything in Web API with a class that inherits from Controller, not just ControllerBase (I'm sure). And the question about the difference(s) may be in another post. I said that because: when I create new controller in my project (.net core 2.1), it inherits from Controller.
– Foo
Nov 10 at 14:45














1 Answer
1






active

oldest

votes

















up vote
1
down vote













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.






share|improve this answer





















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53236137%2fhow-to-use-dependency-injection-in-web-api-controller-class-for-dbset-objects%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    1
    down vote













    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.






    share|improve this answer

























      up vote
      1
      down vote













      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.






      share|improve this answer























        up vote
        1
        down vote










        up vote
        1
        down vote









        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.






        share|improve this answer












        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.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 10 at 14:25









        Ruard van Elburg

        5,09321125




        5,09321125






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53236137%2fhow-to-use-dependency-injection-in-web-api-controller-class-for-dbset-objects%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Schultheiß

            Verwaltungsgliederung Dänemarks

            Liste der Kulturdenkmale in Wilsdruff