« Dapper » : différence entre les versions
De Banane Atomic
Aller à la navigationAller à la recherche
(→Links) |
Aucun résumé des modifications |
||
Ligne 14 : | Ligne 14 : | ||
dotnet add package MySQLConnection # for MySqlConnection | dotnet add package MySQLConnection # for MySqlConnection | ||
</kode> | </kode> | ||
= Dependency Injection = | |||
<filebox fn='Program.cs'> | |||
var connectionString = builder.Configuration.GetConnectionString("MyDatabase"); | |||
builder.Services.AddSingleton<IDbConnectionFactory, MySqlConnectionFactory>( | |||
_ => new MySqlConnectionFactory(connectionString)); | |||
</filebox> | |||
<filebox fn='DataAccess/MySqlConnectionFactory.cs'> | |||
public class MySqlConnectionFactory : IDbConnectionFactory | |||
{ | |||
private readonly string connectionString; | |||
public MySqlConnectionFactory(string connectionString) | |||
{ | |||
this.connectionString = connectionString; | |||
} | |||
public IDbConnection CreateConnection() => new MySqlConnection(connectionString); | |||
} | |||
</filebox> | |||
<filebox fn='DataAccess/IDbConnectionFactory.cs' collapsed> | |||
public interface IDbConnectionFactory | |||
{ | |||
IDbConnection CreateConnection(); | |||
} | |||
</filebox> |
Version du 13 août 2023 à 15:02
Links
Description
Dapper is ideal for scenarios where performance is critical and developers want fine-grained control over the database operations.
Dapper is also easy to learn and use comparing to EF.
Nuget packages
dotnet add package Dapper dotnet add package MySQLConnection # for MySqlConnection |
Dependency Injection
Program.cs |
var connectionString = builder.Configuration.GetConnectionString("MyDatabase"); builder.Services.AddSingleton<IDbConnectionFactory, MySqlConnectionFactory>( _ => new MySqlConnectionFactory(connectionString)); |
DataAccess/MySqlConnectionFactory.cs |
public class MySqlConnectionFactory : IDbConnectionFactory { private readonly string connectionString; public MySqlConnectionFactory(string connectionString) { this.connectionString = connectionString; } public IDbConnection CreateConnection() => new MySqlConnection(connectionString); } |
DataAccess/IDbConnectionFactory.cs |
public interface IDbConnectionFactory { IDbConnection CreateConnection(); } |