From d482c786535c52076a77871df618fc5521fc3746 Mon Sep 17 00:00:00 2001 From: Rick Anderson <3605364+Rick-Anderson@users.noreply.github.com> Date: Thu, 12 Oct 2023 14:22:06 -1000 Subject: [PATCH] keyed svs --- samples/KeyedServices/KeyedServices.csproj | 9 ++++ samples/KeyedServices/Program.cs | 51 ++++++++++++++++++++++ samples/KeyedServices/appsettings.json | 9 ++++ 3 files changed, 69 insertions(+) create mode 100644 samples/KeyedServices/KeyedServices.csproj create mode 100644 samples/KeyedServices/Program.cs create mode 100644 samples/KeyedServices/appsettings.json diff --git a/samples/KeyedServices/KeyedServices.csproj b/samples/KeyedServices/KeyedServices.csproj new file mode 100644 index 0000000..1b28a01 --- /dev/null +++ b/samples/KeyedServices/KeyedServices.csproj @@ -0,0 +1,9 @@ + + + + net8.0 + enable + enable + + + diff --git a/samples/KeyedServices/Program.cs b/samples/KeyedServices/Program.cs new file mode 100644 index 0000000..14378f9 --- /dev/null +++ b/samples/KeyedServices/Program.cs @@ -0,0 +1,51 @@ +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.SignalR; + +var builder = WebApplication.CreateBuilder(args); + +builder.Services.AddKeyedSingleton("big"); +builder.Services.AddKeyedSingleton("small"); +builder.Services.AddControllers(); + +var app = builder.Build(); + +app.MapGet("/big", ([FromKeyedServices("big")] ICache bigCache) => bigCache.Get("date")); + +app.MapGet("/small", ([FromKeyedServices("small")] ICache smallCache) => smallCache.Get("date")); + +app.MapControllers(); + +app.Run(); + +public interface ICache +{ + object Get(string key); +} +public class BigCache : ICache +{ + public object Get(string key) => $"Resolving {key} from big cache."; +} + +public class SmallCache : ICache +{ + public object Get(string key) => $"Resolving {key} from small cache."; +} + +[ApiController] +[Route("/cache")] +public class CustomServicesApiController : Controller +{ + [HttpGet("big-cache")] + public ActionResult GetOk([FromKeyedServices("big")] ICache cache) + { + return cache.Get("data-mvc"); + } +} + +public class MyHub : Hub +{ + public void Method([FromKeyedServices("small")] ICache cache) + { + Console.WriteLine(cache.Get("signalr")); + } +} \ No newline at end of file diff --git a/samples/KeyedServices/appsettings.json b/samples/KeyedServices/appsettings.json new file mode 100644 index 0000000..10f68b8 --- /dev/null +++ b/samples/KeyedServices/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +}