user4154282
user4154282

Reputation:

ASP.NET REST API without Entity Framework but with DAO's

I am new to .NET and I am trying to create a REST API without the Entity Framework or whatever.

I wanted to write my own DAO's, but what I cannot figure out is, how I should access the DAO's from the APIControllers (ControllerBase) where the API request are coming in.

So basically, my question is, what is the best or a common way to access the DAO's from the ControllerBase classes. (ControllerBase class is the class where the API calls are coming in i.e.: get, getById, add, delete, update)

To picture my issue:

       -----------------------------
 ------ControllerBase for Students 
|      -----------------------------
|
| How can I access my DAO methods (get, update, delete, add,...) from
| the ControllerBase class. I look for a common way.
|
|       ------------
 ---->   StudentDAO
        ------------

Of course I could instantiate a DAO object in the ControllerBase, but I think there should be a better solution. Also I could create static methods, but I would like to know if there are better solutions.

Hopefully you understand my question.

Upvotes: 0

Views: 1430

Answers (2)

buttercup_byte
buttercup_byte

Reputation: 11

Depending if you are using .NET Core, you should be able to just create the interface with the correct signatures, and then define a service with the actual implementation.

"Inject" that interface into your controller and you will be able to use that DAO anywhere within the controller. Remember to register your interface with the DI in your "Startup.cs" class though.

Dependency Injection will prevent the use of instantiating the class and from making things static.

interface IDAO
{
 // method signatures and properties here for the DAO
}


class DAO : IDAO
{ 
  // specific code about the DAO. such as connection to DBs, methods, props, etc...
} 

class StudentController:ControllerBase
{
    private readonly IDAO _dao
    public StudentController(IDAO dao)
    {
      _dao = dao;
    }
}

When it comes to registering in the Startupfile, take a look at the Transient/Scoped/Singleton lifecycles and pick from there what you think is the best fit.

Upvotes: 1

Mykola Zaiarnyi
Mykola Zaiarnyi

Reputation: 18

You can try to create an interface and class that will operate with DAO's, then register it in Dependency Injection in ConfigureServices method of Startup class.

public void ConfigureServices(IServiceCollection services) {
        services.AddScoped<IStudentDao, StudentDao>()
    }

Then in controller you need to create field of IStudentDao type and constructor.

public class StudentController : ControllerBase {
    private readonly IStudentDao _dao;

public StudentController(IStudentDao dao) {
        _dao = dao;
}

Upvotes: 0

Related Questions