Database access with Dependency Injection (DI)

Starting from this version, static Starcounter 2.x style Db class has been removed.

The current release introduces new SC framework API based on dependency injection (DI), which has been for long time requested by the majority of our users.

In this release, database access and operations are provided via two main Starcounter services.

  • Starcounter.Nova.Hosting.ITransactor - provides database transactions and data manipulation (DML) API.

  • Starcounter.Nova.Hosting.IDdlExecutor - provides data definition (DML) API.

The purpose of the current release is to polish the new SC framework API and approve it with the customers. In the future public releases we plan to introduce a so-called static API serving same purpose as Db class in Starcounter 2.x, yet free from known flaws and strictly built on top of the new SC framework API.

Why Dependency Injection (DI)?

One of the major disadvantages of the static classes usage is inability to test such code with unit tests. With Dependency Injection it is possible to mock tested services and write unit tests for the application.

Furthermore, current approach reduces possibilities for invalid database access:

  • Attempt to create a new database object without a transaction.

  • Attempt to access a database object without a transaction.

  • Attempt to execute a DDL statement within a transaction.

Read more about Dependency Injection - Design Patterns Explained – Dependency Injection with Code Examples.

Examples

Database DML & DDL operations

Previously Db.SQL method was responsible for all kind of SQL statements. This led to a confusion, when developers tried to execute DDL statements within a transaction and access database without a transaction.

With introduction of the ITransactor and IDdlExecutor database services it is easier to follow the code flow and database interaction. The Insert and Get database operations are only available within a transaction.

ASP.NET Core DbAccessController sample

Last updated