Open Closed

DbContext from HttpApi #279


User avatar
0
robb created

I see from the sample applications how to add a controller method to the HttpApi project (TestController)

How do you use dependency injection to get access to the DbContext?

Actually, I have 2 DbContexts I want to inject into my HttpApi controller, so I can perform database read/writes.


4 Answer(s)
  • User Avatar
    0
    gterdem created
    Senior .NET Developer

    Hello @robb,

    Directly injecting the DbContexts will violate the Seperation of Concern principle. As much as it would seem to be a fast way to get things moving; it will cause more problems in the future.

    Suggested way is to move this logic to application layer. You can inject different repositories from different dbcontexts and handle it on application layer. Then inject the application layer to Api or wherever else you want to.

    I hope it was helpful.

  • User Avatar
    0
    liangshiwei created
    Support Team Fullstack Developer

    gterdem's answer is absolutely right.

    However , if you want get dbcontext, you can see the docuemnt : https://docs.abp.io/en/abp/latest/Entity-Framework-Core#access-to-the-ef-core-api

  • User Avatar
    0
    robb created

    Can you please provide documentation or an example of how to inject and utilize the application layer into the HttpApi?

  • User Avatar
    0
    gterdem created
    Senior .NET Developer

    Hello, it is pretty straightforward; here is a link from abp-sample repository BookStore sample injecting appService into api controller.

    Keep on mind, when you implement your appService, you will already have api endpoints thanks to dynamic proxy. So you may not need to add anything to HttpApi. See aslo Auto API Controllers.

Made with ❤️ on ABP v9.1.0-preview. Updated on December 05, 2024, 12:19