GithubHelp home page GithubHelp logo

pimbrouwers / lunchpail Goto Github PK

View Code? Open in Web Editor NEW
36.0 5.0 14.0 45 KB

.NET Standard Unit of Work implementation for ADO.NET

License: GNU General Public License v3.0

C# 90.41% PowerShell 9.59%
ado ioc-container unit-of-work repository-pattern ado-net

lunchpail's Introduction

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.

Note the invocation of dbContext.Commit() which must occur after every interaction is complete to ensure proper disposal of the connection. This is true whether the interaction is a read or write.

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);
    dbContext.Commit(); // You MUST call commit after all interactions

    return product;
  }
}

Built with โ™ฅ by Pim Brouwers in Toronto, ON.

lunchpail's People

Contributors

johngrant avatar pimbrouwers avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

lunchpail's Issues

Implementation question

@pimbrouwers Please help me on below points.

  1. May i know why we have to commit (dbContext.Commit();) the transaction for SQL statements which only get the information from database (Like Read operation). Can we ignore Begin Transaction for operations like Read from SQL.

  2. I am using Dapper as middle layer. I have registered the context exactly like how you provided the instructions in startup.cs file. The problem that i am seeing here is with in same controller method call if i am making two database calls (both are read), First call is working fine but the second one is throwing below exception as i believe context was already closed due to
    commit was called after completing the fist DB call. Please let me know if i am missing anything.

System.InvalidOperationException: The ConnectionString property has not been initialized.
at System.Data.SqlClient.SqlConnection.PermissionDemand()

  1. Any async call being made with this code resulted in below exception. Please guide me how to invoke async calls.

    DB call: await Connection.QueryAsync(sQuery,transaction:Transaction);

System.InvalidOperationException: Invalid operation. The connection is closed.
at System.Data.SqlClient.SqlCommand.<>c.b__122_0(Task`1 result)

  1. I am new to .net core world. As per below IOC registration, according to my understanding every time application gets a new request then connection will be opened. It is possible some requests don't need a database connection in that case application is opening a SQL connection but it will not be closed. Please let me know if my understanding is correct.

services.AddTransient(options =>
{
var builder = new SqlConnectionStringBuilder(Configuration.GetConnectionString("DefaultConnectionString"));

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

                conn.Open();
                return conn;
            });
        });

Please help.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.