From 88cf417d875e20da8ed4c31b383b8a8d9d520e09 Mon Sep 17 00:00:00 2001 From: nivalxer Date: Fri, 23 Feb 2024 18:22:12 +0800 Subject: [PATCH] add autofac KeyedServiceTests. Signed-off-by: nivalxer --- .../AspectCore.Extensions.Autofac.Test.csproj | 15 +--- .../KeyedServiceTests.cs | 73 +++++++++++++++++++ 2 files changed, 74 insertions(+), 14 deletions(-) create mode 100644 tests/AspectCore.Extensions.Autofac.Test/KeyedServiceTests.cs diff --git a/tests/AspectCore.Extensions.Autofac.Test/AspectCore.Extensions.Autofac.Test.csproj b/tests/AspectCore.Extensions.Autofac.Test/AspectCore.Extensions.Autofac.Test.csproj index d57e83ed..a5db1aa8 100644 --- a/tests/AspectCore.Extensions.Autofac.Test/AspectCore.Extensions.Autofac.Test.csproj +++ b/tests/AspectCore.Extensions.Autofac.Test/AspectCore.Extensions.Autofac.Test.csproj @@ -17,22 +17,9 @@ - - - - - - - - - - - + - - - all diff --git a/tests/AspectCore.Extensions.Autofac.Test/KeyedServiceTests.cs b/tests/AspectCore.Extensions.Autofac.Test/KeyedServiceTests.cs new file mode 100644 index 00000000..8d5da1f2 --- /dev/null +++ b/tests/AspectCore.Extensions.Autofac.Test/KeyedServiceTests.cs @@ -0,0 +1,73 @@ +using System.Threading.Tasks; +using AspectCore.DependencyInjection; +using AspectCore.DynamicProxy; +using AspectCore.Extensions.Autofac; +using AspectCore.Extensions.DependencyInjection; +using Autofac; +using Autofac.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; +using Xunit; + +namespace AspectCoreTest.Autofac; + +public class KeyedServiceTests +{ + public class InterceptKey : AbstractInterceptorAttribute + { + private int _key; + + public InterceptKey(int key) + { + _key = key; + } + + public override async Task Invoke(AspectContext context, AspectDelegate next) + { + await context.Invoke(next); + context.ReturnValue = _key; + } + } + + public interface IKeydService + { + int Get(); + int GetIntercept(); + } + + public class KeydService : IKeydService + { + private int _current = 0; + public int Get() + { + _current++; + return _current; + } + + [InterceptKey(1000)] + public int GetIntercept() + { + return 2; + } + } +#if NET8_0_OR_GREATER + [Fact] + public void GetKeydService_WithServiceProvider() + { + var services = new ServiceCollection(); + var builder = new ContainerBuilder(); + builder.RegisterDynamicProxy(); + services.AddKeyedScoped("key1"); + services.AddKeyedScoped("key2"); + builder.Populate(services); + var serviceProvider = new AutofacServiceProvider(builder.Build()); + var keydService = serviceProvider.GetKeyedService("key1"); + Assert.Equal(1, keydService.Get()); + Assert.Equal(1000, keydService.GetIntercept()); + + var keyd2Service = serviceProvider.GetKeyedService("key2"); + //不同实例 + Assert.Equal(1, keyd2Service.Get()); + Assert.Equal(1000, keyd2Service.GetIntercept()); + } +#endif +} \ No newline at end of file