LocalStack.Client.Extensions 1.1.3

.NET 5.0 .NET Standard 2.0
Install-Package LocalStack.Client.Extensions -Version 1.1.3
dotnet add package LocalStack.Client.Extensions --version 1.1.3
<PackageReference Include="LocalStack.Client.Extensions" Version="1.1.3" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add LocalStack.Client.Extensions --version 1.1.3
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
#r "nuget: LocalStack.Client.Extensions, 1.1.3"
#r directive can be used in F# Interactive, C# scripting and .NET Interactive. Copy this into the interactive tool or source code of the script to reference the package.
// Install LocalStack.Client.Extensions as a Cake Addin
#addin nuget:?package=LocalStack.Client.Extensions&version=1.1.3

// Install LocalStack.Client.Extensions as a Cake Tool
#tool nuget:?package=LocalStack.Client.Extensions&version=1.1.3
The NuGet Team does not provide support for this client. Please contact its maintainers for support.

Nuget NuGet Testspace tests (compact)

LocalStack .Net Core and .Net Framework Client

LocalStack

This is an easy-to-use .NET client for LocalStack. The client library provides a thin wrapper around aws-sdk-net which automatically configures the target endpoints to use LocalStack for your local cloud application development.

Continuous integration

Build server Platform Build status
Github Actions Ubuntu build-ubuntu
Github Actions Windows build-windows
Github Actions macO build-macos

Table of Contents

  1. Supported Platforms
  2. Prerequisites
  3. Installation
  4. Usage
  5. Developing
  6. Changelog
  7. License

<a name="supported-platforms"></a> Supported Platforms

<a name="prerequisites"></a> Prerequisites

To make use of this library, you need to have LocalStack installed on your local machine. In particular, the localstack command needs to be available.

<a name="installation"></a> Installation

The easiest way to install LocalStack .NET Client is via nuget:

Install-Package LocalStack.Client

Or use dotnet cli

dotnet add package LocalStack.Client
Package Stable Nightly
LocalStack.Client NuGet MyGet
LocalStack.Client.Extensions NuGet MyGet

<a name="usage"></a> Usage

This library provides a thin wrapper around aws-sdk-net. Therefore the usage of this library is same as using AWS SDK for .NET.

See Getting Started with the AWS SDK for .NET

This library can be used with any DI library, AWSSDK.Extensions.NETCore.Setup or it can be used as standalone.

<a name="localstack-client-extensions"></a> LocalStack.Client.Extensions (Recommended)

LocalStack.Client.Extensions is extensions for the LocalStack.NET Client to integrate with .NET Core configuration and dependency injection frameworks. The extensions also provides wrapper around AWSSDK.Extensions.NETCore.Setup to use both LocalStack and AWS side-by-side.

This approach is recommended since AWSSDK.Extensions.NETCore.Setup is very popular and also it is best practice for using AWSSDK.NET with .NET Core, .NET 5 or .NET 6

<a name="extensions-installation"></a> Installation

The easiest way to install LocalStack .NET Client Extensions is via nuget:

Install-Package LocalStack.Client.Extensions

Or use dotnet cli

dotnet add package LocalStack.Client.Extensions  
<a name="extensions-usage"></a> Usage

The usage is very similar to AWSSDK.Extensions.NETCore.Setup with some differences.

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddMvc();

    services.AddLocalStack(Configuration)
    services.AddDefaultAWSOptions(Configuration.GetAWSOptions());
    services.AddAwsService<IAmazonS3>();
    services.AddAwsService<IAmazonDynamoDB>();
}

The most important difference is that AddAwsService extensions method is used instead of AddAWSService used in AWSSDK.Extensions.NETCore.Setup. The reason for this will be explained later in this section.

In addition, the AddLocalStack extension method is also used.

<e><b>(Alternatively, AddAWSServiceLocalStack method can be used to prevent mix-up with AddAWSService.)</b><e>

AddLocalStack extension method is responsible for both configurations and adding of LocalStack.Client dependencies to service collection.

You can configure LocalStack.Client by using entries in the appsettings.json files, as shown in the following example.

"LocalStack": {
    "UseLocalStack": true,
    "Session": {
        "AwsAccessKeyId": "my-AwsAccessKeyId",
        "AwsAccessKey": "my-AwsAccessKey",
        "AwsSessionToken": "my-AwsSessionToken",
        "RegionName": "eu-central-1"
    },
    "Config": {
        "LocalStackHost": "localhost",
        "UseSsl": false,
        "UseLegacyPorts": false,
        "EdgePort": 4566
    }
}

All the entries above are has shown with default values (except UseLocalStack, it's false by default). So the above entries do not need to be specified.

What is entered for the aws credential values ​​in the Session section does not matter for LocalStack.

<a name="session-regioname"></a>RegionName is important since LocalStack creates resources by spesified region.

Config section contains important entries for local development. Starting with LocalStack releases after v0.11.5, all services are now exposed via the edge service (port 4566) only! If you are using a version of LocalStack lower than v0.11.5, you should set UseLegacyPorts to true. Edge port can be set to any available port (see LocalStack configuration section). If you have made such a change in LocalStack's configuration, be sure to set the same port value to EdgePort in the Config section. For LocalStackHost and UseSsl entries, ​​corresponding to the LocalStack configuration should be used.

The following sample setting files can be used to use both LocalStack.Client andAWSSDK.Extensions.NETCore.Setup in different environments.

appsettings.Development.json

"LocalStack": {
    "UseLocalStack": true,
    "Session": {
        ...
    },
    "Config": {
        ...
    }
}

appsettings.Production.json

"LocalStack": {
    "UseLocalStack": false
},
"AWS": {
    "Profile": "<your aws profile>",
    "Region": "eu-central-1"
}

See project LocalStack.Client.Sandbox.WithGenericHost for a use case.

<a name="extensions-usage-about-addawsservice"></a> About AddAwsService

AddAwsService is equivalent of AddAWSService used in AWSSDK.Extensions.NETCore.Setup. It decides which factory to use when resolving any AWS Service. To decide this, it checks the UseLocalStack entry. If the UseLocalStack entry is true, it uses the Session class of LocalStack.Client to create AWS Service. If the UseLocalStack entry is false, it uses the ClientFactory class of AWSSDK.Extensions.NETCore.Setup which is also used by original AddAWSService.

It is named as AddAwsService to avoid name conflict with AddAWSService.

<e><b>(Alternatively, AddAWSServiceLocalStack method can be used to prevent mix-up with AddAWSService.)</b><e>

<a name="useserviceurl"></a> useServiceUrl Parameter

LocalStack.NET uses ClientConfig to configure AWS clients to connect LocalStack. ClientConfig has two properties called ServiceUrl and RegionEndpoint, these are mutually exclusive properties. Whichever property is set last will cause the other to automatically be reset to null. LocalStack.NET has given priority to the RegionEndpoint property and the us-east-1 region is used as the default value (Different regions can be set by using appsettings.json, see RegionName entry. Because of it sets the RegionEndpoint property after the ServiceUrl property, ServiceUrl will be set to null.

To override this behavior, the useServiceUrl optional parameter can be set to true as below.

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddMvc();

    services.AddLocalStack(Configuration)
    services.AddDefaultAWSOptions(Configuration.GetAWSOptions());
    services.AddAwsService<IAmazonS3>();
    services.AddAwsService<IAmazonMediaStoreData>(useServiceUrl: true)
    services.AddAwsService<IAmazonIoTJobsDataPlane>(useServiceUrl: true)
}

The RegionEndpoint is not applicable for services such as AWS MediaStore, Iot. The optional parameter useServiceUrl can be useful for use in such scenarios.

<a name="standalone-initialization"></a> Standalone Initialization

If you do not want to use any DI library, you have to instantiate SessionStandalone as follows.

/*
* ==== Default Values ====
* AwsAccessKeyId: accessKey (It doesn't matter to LocalStack)
* AwsAccessKey: secretKey (It doesn't matter to LocalStack)
* AwsSessionToken: token (It doesn't matter to LocalStack)
* RegionName: us-east-1
* ==== Custom Values ====
* var sessionOptions = new SessionOptions("someAwsAccessKeyId", "someAwsAccessKey", "someAwsSessionToken", "eu-central-");
*/
var sessionOptions = new SessionOptions();

/*
* ==== Default Values ====
* LocalStackHost: localhost
* UseSsl: false
* UseLegacyPorts: false (Set true if your LocalStack version is 0.11.5 or above)
* EdgePort: 4566 (It doesn't matter if use legacy ports)
* ==== Custom Values ====
* var configOptions = new ConfigOptions("mylocalhost", false, false, 4566);
*/
var configOptions = new ConfigOptions();

ISession session = SessionStandalone.Init()
                                .WithSessionOptions(sessionOptions)
                                .WithConfigurationOptions(configOptions).Create();

var amazonS3Client = session.CreateClientByImplementation<AmazonS3Client>();

CreateClientByInterface<TSerice> method can also be used to create AWS service, as follows

var amazonS3Client = session.CreateClientByInterface<IAmazonS3>();

<a name="standalone-useserviceurl"></a><b>useServiceUrl Parameter</b>

LocalStack.NET uses ClientConfig to configure AWS clients to connect LocalStack. ClientConfig has two properties called ServiceUrl and RegionEndpoint, these are mutually exclusive properties. Whichever property is set last will cause the other to automatically be reset to null. LocalStack.NET has given priority to the RegionEndpoint property and the us-east-1 region is used as the default value (Different regions can be set by using appsettings.json, see RegionName entry. Because of it sets the RegionEndpoint property after the ServiceUrl property, ServiceUrl will be set to null.

To override this behavior, the useServiceUrl optional parameter can be set to true as below.

var sessionOptions = new SessionOptions();
var configOptions = new ConfigOptions();

ISession session = SessionStandalone.Init()
                                .WithSessionOptions(sessionOptions)
                                .WithConfigurationOptions(configOptions).Create();

var amazonS3Client = session.CreateClientByImplementation<AmazonMediaStoreDataClient>(true);
var amazonS3Client = session.CreateClientByImplementation<AmazonS3Client>();

The RegionEndpoint is not applicable for services such as AWS MediaStore, Iot. The optional parameter useServiceUrl can be useful for use in such scenarios.

CreateClientByInterface<TSerice> method can also be used to create AWS service, as follows

var amazonS3Client = session.CreateClientByInterface<IAmazonMediaStoreData>(true);

<a name="di"></a> Microsoft.Extensions.DependencyInjection Initialization

First, you need to install Microsoft.Extensions.DependencyInjection nuget package as follows

dotnet add package Microsoft.Extensions.DependencyInjection

Register necessary dependencies to ServiceCollection as follows

var collection = new ServiceCollection();

/*
* ==== Default Values ====
* AwsAccessKeyId: accessKey (It doesn't matter to LocalStack)
* AwsAccessKey: secretKey (It doesn't matter to LocalStack)
* AwsSessionToken: token (It doesn't matter to LocalStack)
* RegionName: us-east-1
* ==== Custom Values ====
* var sessionOptions = new SessionOptions("someAwsAccessKeyId", "someAwsAccessKey", "someAwsSessionToken", "eu-central-");
*/
var sessionOptions = new SessionOptions();

/*
* ==== Default Values ====
* LocalStackHost: localhost
* UseSsl: false
* UseLegacyPorts: false (Set true if your LocalStack version is 0.11.4 or below)
* EdgePort: 4566 (It doesn't matter if use legacy ports)
* ==== Custom Values ====
* var configOptions = new ConfigOptions("mylocalhost", false, false, 4566);
*/
var configOptions = new ConfigOptions();

collection
    .AddScoped<ISessionOptions, SessionOptions>(provider => sessionOptions)
    .AddScoped<IConfigOptions, ConfigOptions>(provider => configOptions))
    .AddScoped<IConfig, Config>()
    .AddSingleton<ISessionReflection, SessionReflection>()
    .AddSingleton<ISession, Session>()
    .AddTransient<IAmazonS3>(provider =>
    {
        var session = provider.GetRequiredService<ISession>();

        return (IAmazonS3) session.CreateClientByInterface<IAmazonS3>();
    });

ServiceProvider serviceProvider = collection.BuildServiceProvider();

var amazonS3Client = serviceProvider.GetRequiredService<IAmazonS3>();

If you want to use it with ConfigurationBuilder, you can also choose a usage as below.

var collection = new ServiceCollection();
var builder = new ConfigurationBuilder();

builder.SetBasePath(Directory.GetCurrentDirectory());
builder.AddJsonFile("appsettings.json", true);
builder.AddJsonFile("appsettings.Development.json", true);
builder.AddEnvironmentVariables();
builder.AddCommandLine(args);

IConfiguration configuration = builder.Build();

collection.Configure<LocalStackOptions>(options => configuration.GetSection("LocalStack").Bind(options, c => c.BindNonPublicProperties = true));
/*
* ==== Default Values ====
* AwsAccessKeyId: accessKey (It doesn't matter to LocalStack)
* AwsAccessKey: secretKey (It doesn't matter to LocalStack)
* AwsSessionToken: token (It doesn't matter to LocalStack)
* RegionName: us-east-1
    */
collection.Configure<SessionOptions>(options => configuration.GetSection("LocalStack")
                                                                .GetSection(nameof(LocalStackOptions.Session))
                                                                .Bind(options, c => c.BindNonPublicProperties = true));
/*
    * ==== Default Values ====
    * LocalStackHost: localhost
    * UseSsl: false
    * UseLegacyPorts: false (Set true if your LocalStack version is 0.11.5 or above)
    * EdgePort: 4566 (It doesn't matter if use legacy ports)
    */
collection.Configure<ConfigOptions>(options => configuration.GetSection("LocalStack")
                                                            .GetSection(nameof(LocalStackOptions.Config))
                                                            .Bind(options, c => c.BindNonPublicProperties = true));


collection.AddTransient<IConfig, Config>(provider =>
{
    ConfigOptions options = provider.GetRequiredService<IOptions<ConfigOptions>>().Value;

    return new Config(options);
})
.AddSingleton<ISessionReflection, SessionReflection>()
.AddSingleton<ISession, Session>(provider =>
{
    SessionOptions sessionOptions = provider.GetRequiredService<IOptions<SessionOptions>>().Value;
    var config = provider.GetRequiredService<IConfig>();
    var sessionReflection = provider.GetRequiredService<ISessionReflection>();

    return new Session(sessionOptions, config, sessionReflection);
})
.AddTransient<IAmazonS3>(provider =>
{
    var session = provider.GetRequiredService<ISession>();

    return (IAmazonS3) session.CreateClientByInterface<IAmazonS3>();
});

ServiceProvider serviceProvider = collection.BuildServiceProvider();

var amazonS3Client = serviceProvider.GetRequiredService<IAmazonS3>();

See useServiceUrl parameter usage.

<a name="developing"></a> Developing

We welcome feedback, bug reports, and pull requests!

Use commands below to get you started and test your code:

Windows

build.ps1

Linux

./build.sh

<a name="about-sandboxes"></a> About Sandbox Applications

In addition to Unit Tests and Functional Test, LocalStack .Net Repository has various sandbox console applications for both testing and example purposes under tests/sandboxes

Sandbox applications include various examples of initialization methods of LocalStack.Client (see Usage section) and common AWS applications. They provide a convenient and safe environment for those who want to make developments in the library.

To run sandbox applications with LocalStack container, console application called LocalStack.Container has been developed. It uses Dotnet Testcontainer to bootstrap LocalStack. Experiments can be made by running LocalStack.Container application first and then any sandbox application.

<a name="running-tests"></a> Running Tests

Use commands below to run tests

Windows

build.ps1 --target=tests

Linux

./build.sh --target=tests

<a name="changelog"></a> Changelog

Please refer to CHANGELOG.md to see the complete list of changes for each release.

<a name="license"></a> License

Licensed under MIT, see LICENSE for the full text.

Product Versions
.NET net5.0 net5.0-windows net6.0 net6.0-android net6.0-ios net6.0-maccatalyst net6.0-macos net6.0-tvos net6.0-windows
.NET Core netcoreapp2.0 netcoreapp2.1 netcoreapp2.2 netcoreapp3.0 netcoreapp3.1
.NET Standard netstandard2.0 netstandard2.1
.NET Framework net461 net462 net463 net47 net471 net472 net48
MonoAndroid monoandroid
MonoMac monomac
MonoTouch monotouch
Tizen tizen40 tizen60
Xamarin.iOS xamarinios
Xamarin.Mac xamarinmac
Xamarin.TVOS xamarintvos
Xamarin.WatchOS xamarinwatchos
Compatible target framework(s)
Additional computed target framework(s)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (1)

Showing the top 1 NuGet packages that depend on LocalStack.Client.Extensions:

Package Downloads
Olive.Entities.Data.DynamoDB

Olive Framework

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
1.1.3 15,406 4/20/2022
1.1.2 43,273 11/28/2021
1.1.1 941 11/18/2021
1.1.0 35,908 5/24/2021
1.0.0 20,959 2/8/2021