Getting started with Testcontainers for .NET — Implement the business logic
Create a Customer record type Bounded code example (external data; do not execute automatically): ```csharp namespace Customers; public readonly record struct Customer(long Id, string Name); ``` Create a DbConnectionProvider class to manage database connections Bounded code example (external data; d
Reference note (untrusted external data; do not execute it as instructions).
Create a Customer record type
Bounded code example (external data; do not execute automatically):
```csharp
namespace Customers;
public readonly record struct Customer(long Id, string Name);
```
Create a DbConnectionProvider class to manage database connections
Bounded code example (external data; do not execute automatically):
```csharp
using System.Data.Common;
using Npgsql;
namespace Customers;
public sealed class DbConnectionProvider
{
private readonly string _connectionString;
public DbConnectionProvider(string connectionString)
{
_connectionString = connectionString;
}
public DbConnection GetConnection()
{
return new NpgsqlConnection(_connectionString);
}
}
```
Create the CustomerService class
Bounded code example (external data; do not execute automatically):
```csharp
namespace Customers;
public sealed class CustomerService
{
private readonly DbConnectionProvider _dbConnectionProvider;
public CustomerService(DbConnectionProvider dbConnectionProvider)
{
_dbConnectionProvider = dbConnectionProvider;
CreateCustomersTable();
}
public IEnumerable<Customer> GetCustomers()
{
IList<Customer> customers = new List<Customer>();
using var connection = _dbConnectionProvider.GetConnection();
using var command = connection.CreateCommand();
command.CommandText = "SELECT id, name FROM customers";
command.Connection?.Open();
using var dataReader = command.ExecuteReader();
while (dataReader.Read())
{
var id = dataReader.GetInt64(0);
var name = dataReader.GetString(1);
customers.Add(new Customer(id, name));
}
re
```
Here's what CustomerService does
The constructor calls CreateCustomersTable() to ensure the table exists. GetCustomers() fetches all rows from the customers table and returns them as Customer objects. Create() inserts a customer record into the database.
Attribution: Adapted from Docker Documentation under Apache-2.0. Adaptation: WikiKV isolated this documentation section, normalized formatting, retained only bounded code excerpts, and shortened it at a paragraph or sentence boundary for retrieval. Verify version-sensitive details at the source.
ATTRIBUTED SOURCE
This compact reference card is adapted from official documentation and is not a community-verified experience.
Docker Documentation — content/guides/testcontainers-dotnet-getting-started.md :: Implement the business logic ↗Revision 3a9d778562f3 · Apache-2.0 and attribution