Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions NatsDistributedCache.sln
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PerfTest", "util\PerfTest\P
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ReadmeExample", "util\ReadmeExample\ReadmeExample.csproj", "{2F16AC9F-97A1-4362-84B4-F03C3EBC6CD6}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NatsHybridCache", "src\NatsHybridCache\NatsHybridCache.csproj", "{F95B33FB-37B3-44F4-9E10-55835A527CA3}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -117,6 +119,18 @@ Global
{2F16AC9F-97A1-4362-84B4-F03C3EBC6CD6}.Release|x64.Build.0 = Release|Any CPU
{2F16AC9F-97A1-4362-84B4-F03C3EBC6CD6}.Release|x86.ActiveCfg = Release|Any CPU
{2F16AC9F-97A1-4362-84B4-F03C3EBC6CD6}.Release|x86.Build.0 = Release|Any CPU
{F95B33FB-37B3-44F4-9E10-55835A527CA3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F95B33FB-37B3-44F4-9E10-55835A527CA3}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F95B33FB-37B3-44F4-9E10-55835A527CA3}.Debug|x64.ActiveCfg = Debug|Any CPU
{F95B33FB-37B3-44F4-9E10-55835A527CA3}.Debug|x64.Build.0 = Debug|Any CPU
{F95B33FB-37B3-44F4-9E10-55835A527CA3}.Debug|x86.ActiveCfg = Debug|Any CPU
{F95B33FB-37B3-44F4-9E10-55835A527CA3}.Debug|x86.Build.0 = Debug|Any CPU
{F95B33FB-37B3-44F4-9E10-55835A527CA3}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F95B33FB-37B3-44F4-9E10-55835A527CA3}.Release|Any CPU.Build.0 = Release|Any CPU
{F95B33FB-37B3-44F4-9E10-55835A527CA3}.Release|x64.ActiveCfg = Release|Any CPU
{F95B33FB-37B3-44F4-9E10-55835A527CA3}.Release|x64.Build.0 = Release|Any CPU
{F95B33FB-37B3-44F4-9E10-55835A527CA3}.Release|x86.ActiveCfg = Release|Any CPU
{F95B33FB-37B3-44F4-9E10-55835A527CA3}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand All @@ -129,5 +143,6 @@ Global
{E2375A65-5A56-4708-997F-2311D9E23FB6} = {0C88DD14-F956-CE84-757C-A364CCF449FC}
{2F8B1224-AAC1-4ABB-BFF6-35AFE1D33E29} = {55AA232E-1A1A-2839-440B-9DCB8E3B1CD6}
{2F16AC9F-97A1-4362-84B4-F03C3EBC6CD6} = {55AA232E-1A1A-2839-440B-9DCB8E3B1CD6}
{F95B33FB-37B3-44F4-9E10-55835A527CA3} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
EndGlobalSection
EndGlobal
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[![NuGet Version](https://img.shields.io/nuget/v/CodeCargo.Nats.DistributedCache?cacheSeconds=3600&color=516bf1)](https://www.nuget.org/packages/CodeCargo.Nats.DistributedCache/)
[![NuGet Version](https://img.shields.io/nuget/v/CodeCargo.NatsDistributedCache?cacheSeconds=3600&color=516bf1)](https://www.nuget.org/packages/CodeCargo.NatsDistributedCache/)

# CodeCargo.Nats.DistributedCache
# CodeCargo.NatsDistributedCache

## Overview

Expand All @@ -20,7 +20,7 @@ A .NET 8+ library for integrating NATS as a distributed cache in ASP.NET Core ap

```bash
# add NATS Distributed Cache
dotnet add package CodeCargo.Nats.DistributedCache
dotnet add package CodeCargo.NatsDistributedCache

# optional - add full NATS.Net (NATS Distributed Cache uses a subset of NATS.Net dependencies)
dotnet add package NATS.Net
Expand All @@ -35,7 +35,7 @@ See the [Full Example here](https://github.com/code-cargo/NatsDistributedCache/t
This is the portion for registering services:

```csharp
using CodeCargo.Nats.DistributedCache;
using CodeCargo.NatsDistributedCache;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using NATS.Client.Core;
Expand Down
4 changes: 2 additions & 2 deletions src/NatsDistributedCache/NatsCache.Log.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
using Microsoft.Extensions.Logging;

namespace CodeCargo.Nats.DistributedCache;
namespace CodeCargo.NatsDistributedCache;

public partial class NatsCache
{
private void LogException(Exception exception) =>
_logger.LogError(EventIds.Exception, exception, "Exception in NatsCache");
_logger.LogError(EventIds.Exception, exception, "Exception in NatsDistributedCache");

private void LogConnected(string bucketName) =>
_logger.LogInformation(EventIds.Connected, "Connected to NATS KV bucket {bucketName}", bucketName);
Expand Down
4 changes: 2 additions & 2 deletions src/NatsDistributedCache/NatsCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
using NATS.Client.KeyValueStore;
using NATS.Net;

namespace CodeCargo.Nats.DistributedCache;
namespace CodeCargo.NatsDistributedCache;

/// <summary>
/// Cache entry for storing in NATS Key-Value Store
Expand Down Expand Up @@ -243,7 +243,7 @@ private Lazy<Task<INatsKVStore>> CreateLazyKvStore() =>
try
{
var kv = _natsConnection.CreateKeyValueStoreContext();
var store = await kv.GetStoreAsync(_bucketName);
var store = await kv.GetStoreAsync(_bucketName).ConfigureAwait(false);
LogConnected(_bucketName);
return store;
}
Expand Down
31 changes: 0 additions & 31 deletions src/NatsDistributedCache/NatsCacheImpl.cs

This file was deleted.

2 changes: 1 addition & 1 deletion src/NatsDistributedCache/NatsCacheOptions.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
using Microsoft.Extensions.Options;

namespace CodeCargo.Nats.DistributedCache
namespace CodeCargo.NatsDistributedCache
{
/// <summary>
/// Configuration options for <see cref="NatsCache"/>.
Expand Down
8 changes: 4 additions & 4 deletions src/NatsDistributedCache/NatsDistributedCache.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,18 @@
<PropertyGroup>
<IsPackable>true</IsPackable>
<Nullable>enable</Nullable>
<RootNamespace>CodeCargo.Nats.DistributedCache</RootNamespace>
<Description>NATS implementation of Microsoft.Extensions.Caching.Distributed.IDistributedCache.</Description>
<RootNamespace>CodeCargo.NatsDistributedCache</RootNamespace>
<Description>NATS implementation of IDistributedCache.</Description>

<!-- Assembly signing (only if key file exists) -->
<SignAssembly Condition="Exists('$(MSBuildThisFileDirectory)..\..\keys\NatsDistributedCache.2025-05-12.snk')">true</SignAssembly>
<AssemblyOriginatorKeyFile Condition="Exists('$(MSBuildThisFileDirectory)..\..\keys\NatsDistributedCache.2025-05-12.snk')">$(MSBuildThisFileDirectory)..\..\keys\NatsDistributedCache.2025-05-12.snk</AssemblyOriginatorKeyFile>

<!-- NuGet metadata -->
<Authors>CodeCargo</Authors>
<Company>CodeCargo</Company>
<Copyright>Copyright © $([System.DateTime]::Now.Year) CodeCargo</Copyright>
<PackageId>CodeCargo.Nats.DistributedCache</PackageId>
<PackageId>CodeCargo.NatsDistributedCache</PackageId>
<PackageTags>distributed cache;hybrid cache;nats</PackageTags>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<PackageReadmeFile>README.md</PackageReadmeFile>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@
using Microsoft.Extensions.Options;
using NATS.Client.Core;

namespace CodeCargo.Nats.DistributedCache;
namespace CodeCargo.NatsDistributedCache;

/// <summary>
/// Extension methods for setting up NATS distributed cache related services in an <see cref="IServiceCollection" />.
/// </summary>
public static class NatsCacheServiceCollectionExtensions
public static class NatsDistributedCacheExtensions
{
/// <summary>
/// Adds NATS distributed caching services to the specified <see cref="IServiceCollection" />.
Expand All @@ -27,19 +27,19 @@ public static IServiceCollection AddNatsDistributedCache(
{
services.AddOptions();
services.Configure(configureOptions);
services.Add(ServiceDescriptor.Singleton<IDistributedCache, NatsCacheImpl>(serviceProvider =>
services.AddSingleton<IDistributedCache>(sp =>
{
var optionsAccessor = serviceProvider.GetRequiredService<IOptions<NatsCacheOptions>>();
var logger = serviceProvider.GetService<ILogger<NatsCache>>();
var optionsAccessor = sp.GetRequiredService<IOptions<NatsCacheOptions>>();
var logger = sp.GetService<ILogger<NatsCache>>();

var natsConnection = connectionServiceKey == null
? serviceProvider.GetRequiredService<INatsConnection>()
: serviceProvider.GetRequiredKeyedService<INatsConnection>(connectionServiceKey);
? sp.GetRequiredService<INatsConnection>()
: sp.GetRequiredKeyedService<INatsConnection>(connectionServiceKey);

return logger != null
? new NatsCacheImpl(optionsAccessor, logger, serviceProvider, natsConnection)
: new NatsCacheImpl(optionsAccessor, serviceProvider, natsConnection);
}));
? new NatsCache(optionsAccessor, logger, natsConnection)
: new NatsCache(optionsAccessor, natsConnection);
});

return services;
}
Expand Down
6 changes: 5 additions & 1 deletion src/NatsDistributedCache/NatsHybridCacheSerializer.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
// even though this is an IHybridCacheSerializer, it's included in Microsoft.Extensions.Caching.Abstractions
// so we can include it in the NatsDistributedCache package instead of NatsHybridCache to give library
// consumers the option to reduce dependencies

using System.Buffers;
using System.Diagnostics.CodeAnalysis;
using Microsoft.Extensions.Caching.Hybrid;
using NATS.Client.Core;

namespace CodeCargo.Nats.DistributedCache;
namespace CodeCargo.NatsDistributedCache;

public readonly struct NatsHybridCacheSerializer<T>(INatsSerialize<T> serializer, INatsDeserialize<T> deserializer)
: IHybridCacheSerializer<T>
Expand Down
43 changes: 43 additions & 0 deletions src/NatsHybridCache/NatsHybridCache.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<IsPackable>true</IsPackable>
<Nullable>enable</Nullable>
<RootNamespace>CodeCargo.NatsHybridCache</RootNamespace>
<Description>Extensions for using HybridCache with NATS.</Description>

<!-- Assembly signing (only if key file exists) -->
<SignAssembly Condition="Exists('$(MSBuildThisFileDirectory)..\..\keys\CodeCargo.2025-05-12.snk')">true</SignAssembly>
<AssemblyOriginatorKeyFile Condition="Exists('$(MSBuildThisFileDirectory)..\..\keys\CodeCargo.2025-05-12.snk')">$(MSBuildThisFileDirectory)..\..\keys\NatsDistributedCache.2025-05-12.snk</AssemblyOriginatorKeyFile>

<!-- NuGet metadata -->
<Authors>CodeCargo</Authors>
<Company>CodeCargo</Company>
<Copyright>Copyright © $([System.DateTime]::Now.Year) CodeCargo</Copyright>
<PackageId>CodeCargo.NatsHybridCache</PackageId>
<PackageTags>distributed cache;hybrid cache;nats</PackageTags>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<PackageReadmeFile>README.md</PackageReadmeFile>
<PackageProjectUrl>https://github.com/code-cargo/NatsDistributedCache</PackageProjectUrl>
<RepositoryUrl>https://github.com/code-cargo/NatsDistributedCache</RepositoryUrl>
<RepositoryType>git</RepositoryType>
<PublishRepositoryUrl>true</PublishRepositoryUrl>
<EmbedUntrackedSources>true</EmbedUntrackedSources>
<IncludeSymbols>true</IncludeSymbols>
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Caching.Hybrid" Version="9.4.0" />
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="8.0.0" PrivateAssets="All" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\src\NatsDistributedCache\NatsDistributedCache.csproj" />
</ItemGroup>

<ItemGroup>
<None Include="..\..\README.md" Pack="true" PackagePath="\" />
</ItemGroup>

</Project>
52 changes: 52 additions & 0 deletions src/NatsHybridCache/NatsHybridCacheExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
using CodeCargo.NatsDistributedCache;
using Microsoft.Extensions.Caching.Hybrid;
using Microsoft.Extensions.DependencyInjection;
using NATS.Client.Core;

namespace CodeCargo.NatsHybridCache;

/// <summary>
/// Extension methods for setting up NATS hybrid cache related services in an <see cref="IServiceCollection" />.
/// </summary>
public static class NatsHybridCacheExtensions
{
/// <summary>
/// Adds NATS hybrid caching to the specified <see cref="IServiceCollection"/>.
/// This registers the NATS distributed cache and configures HybridCache to
/// use the serializer registry from the configured <see cref="INatsConnection"/>.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection"/> to add services to.</param>
/// <param name="configureOptions">An action to configure <see cref="NatsCacheOptions"/>.</param>
/// <param name="connectionServiceKey">If set, resolves a keyed <see cref="INatsConnection"/> instance.</param>
/// <returns>The configured <see cref="IHybridCacheBuilder"/>.</returns>
public static IHybridCacheBuilder AddNatsHybridCache(
this IServiceCollection services,
Action<NatsCacheOptions> configureOptions,
object? connectionServiceKey = null)
{
services.AddNatsDistributedCache(configureOptions, connectionServiceKey);
var builder = services.AddHybridCache();
builder.Services.AddSingleton<IHybridCacheSerializerFactory>(sp =>
{
var natsConnection = connectionServiceKey == null
? sp.GetRequiredService<INatsConnection>()
: sp.GetRequiredKeyedService<INatsConnection>(connectionServiceKey);

return natsConnection.Opts.SerializerRegistry.ToHybridCacheSerializerFactory();
});

return builder;
}

/// <summary>
/// Registers an <see cref="IHybridCacheSerializerFactory"/> created from the
/// provided <see cref="INatsSerializerRegistry"/>.
/// </summary>
/// <param name="builder">The <see cref="IHybridCacheBuilder"/> instance.</param>
/// <param name="serializerRegistry">The <see cref="INatsSerializerRegistry"/> providing serializers.</param>
/// <returns>The <see cref="IHybridCacheBuilder"/> for chaining.</returns>
public static IHybridCacheBuilder AddNatsHybridCacheSerializerFactory(
this IHybridCacheBuilder builder,
INatsSerializerRegistry serializerRegistry) =>
builder.AddSerializerFactory(serializerRegistry.ToHybridCacheSerializerFactory());
}
Loading