Skip to content

pimbrouwers/LunchPail

Repository files navigation

LunchPail

LunchPail is a .NET Standard compliant Unit of Work implementation for ADO.NET. The UoW is the workhorse of the data context, so the project was dubbed "lunch pail" as a reference to blue collar athletes.

NuGet Version Build Status

Getting Started

  1. Register the context within your IoC container (.NET Core shown below using SQL Server):
//startup.cs
public void ConfigureServices(IServiceCollection services)
{
  //rest of code...

  //context
  services.AddTransient<IDbConnectionFactory>(options =>
  {
    var builder = new SqlConnectionStringBuilder(Configuration.GetConnectionString("DefaultConnection"));

    return new DbConnectionFactory(() =>
    {
      var conn = new SqlConnection(builder.ConnectionString);

      conn.Open();
      return conn;
    });
  });
  services.AddScoped<IDbContext, DbContext>();

  //repositories (we'll add this later)
}
  1. Create a domain class to represents your database object.
public class Product
{
  public int Id { get; set; }
  public string Name { get; set; }
}
  1. Create a repository with a dependency on IDbContext
public interface IProductRepository
{
  Task<Product> Read (int id);
}

public class ProductRepository : DbRepository
{
  public ProductRepository(IDbContext dbContext) : base(dbContext) { }

  public Product Read(int id)
  {
    return Connection.QuerySingleOrDefault<Product>("select * from dbo.Product where Id = @id", new { id }, transaction: Transaction);
  }
}
  1. Register the repository with your IoC container (.NET Core shown below):
//startup.cs
public void ConfigureServices(IServiceCollection services)
{
  //repositories
  services.AddScoped<IProductRepository, ProductRepository>();
}
  1. With the context and repository registered, you're free to inject this into your controller or service layer.
public class ProductService
{
  private readonly IDbContext dbContext;
  private readonly IProductRepository productRepository;

  public ProductService (
    IDbContext dbContext,
    IProductRepository productRepository)
  {
    this.dbContext = dbContext;
    this.productRepository = productRepository;
  }

  public Product Read(int id)
  {
    var product = productRepository.Read(id);
    return product;
  }
}

About

.NET Standard Unit of Work implementation for ADO.NET

Topics

Resources

License

Stars

Watchers

Forks

Contributors 2

  •  
  •