Table of Contents

Dependency Injection

An alternative to using the static classes to access the builders and settings is via dependency injection. Use the Dapper.SimpleSqlBuilder.DependencyInjection NuGet package instead of the default package. The library supports the default dependency injection pattern in .Net Core.

using Dapper.SimpleSqlBuilder.DependencyInjection;

services.AddSimpleSqlBuilder();

Usage in a class.

class MyClass
{
    private readonly simpleBuilder;

    public MyClass(ISimpleBuilder simpleBuilder)
    {
        this.simpleBuilder = simpleBuilder;
    }

    public void MyMethod()
    {
        int id = 10;
        var builder = simpleBuilder.Create($"SELECT * FROM User WHERE Id = {id}");

        // Other code below .....
    }

    public void MyMethod2()
    {
        int id = 10;
        var builder = simpleBuilder.CreateFluent()
            .Select($"*")
            .From($"User")
            .Where($"Id = {id}");

        // Other code below .....
    }
}

Configuring Builder Options

You can configure the builder settings and the ISimpleBuilder instance service lifetime via the SimpleBuilderOptions class. There are various ways to configure the options as shown below.

Configuring Options via appsettings.json

{
  "SimpleSqlBuilder": {
    "DatabaseParameterNameTemplate": "p",
    "DatabaseParameterPrefix": "@",
    "ReuseParameters": false,
    "UseLowerCaseClauses": false
  }
}
services.AddSimpleSqlBuilder(
    // Optional. Default is ServiceLifetime.Singleton
    serviceLifeTime = ServiceLifetime.Singleton);

Configuring Options via code

services.AddSimpleSqlBuilder(
    configure =>
    {
        configure.DatabaseParameterNameTemplate = "param"; // Optional. Default is "p"
        configure.DatabaseParameterPrefix = ":"; // Optional. Default is "@"
        configure.ReuseParameters = true; // Optional. Default is "false"
        configure.UseLowerCaseClauses = true; // Optional. Default is "false". This is only applicable to the fluent builder
    },
    // Optional. Default is ServiceLifetime.Singleton
    serviceLifeTime = ServiceLifetime.Scoped);