From ddb51417a969bd603cf2ac27b282863c3a836933 Mon Sep 17 00:00:00 2001 From: papadi Date: Fri, 21 Apr 2023 16:41:34 +0200 Subject: [PATCH] Add method to get service by Type --- .../Mapster.DependencyInjection.Tests/InjectionTest.cs | 8 ++++++++ .../Mapster.DependencyInjection/TypeAdapterExtensions.cs | 7 ++++++- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/Mapster.DependencyInjection/Mapster.DependencyInjection.Tests/InjectionTest.cs b/Mapster.DependencyInjection/Mapster.DependencyInjection.Tests/InjectionTest.cs index c8f9a3a..afe3d26 100644 --- a/Mapster.DependencyInjection/Mapster.DependencyInjection.Tests/InjectionTest.cs +++ b/Mapster.DependencyInjection/Mapster.DependencyInjection.Tests/InjectionTest.cs @@ -28,6 +28,10 @@ public void Injection() var poco = new Poco {Id = "bar"}; var dto = mapper.Map(poco); dto.Name.ShouldBe("foo"); + + mapper = (IMapper)scope.ServiceProvider.GetService(typeof(IMapper)); + dto = mapper.Map(poco); + dto.Name.ShouldBe("foo"); } } @@ -50,6 +54,10 @@ public void NoServiceAdapter_InjectionError() var poco = new Poco {Id = "bar"}; var dto = mapper.Map(poco); dto.Name.ShouldBe("foo"); + + mapper = scope.ServiceProvider.GetService(); + dto = mapper.Map(poco); + dto.Name.ShouldBe("foo"); } } diff --git a/Mapster.DependencyInjection/Mapster.DependencyInjection/TypeAdapterExtensions.cs b/Mapster.DependencyInjection/Mapster.DependencyInjection/TypeAdapterExtensions.cs index f715bce..1a567c2 100644 --- a/Mapster.DependencyInjection/Mapster.DependencyInjection/TypeAdapterExtensions.cs +++ b/Mapster.DependencyInjection/Mapster.DependencyInjection/TypeAdapterExtensions.cs @@ -12,11 +12,16 @@ internal static U GetValueOrDefault(this IDictionary dict, T key) } public static TService GetService(this MapContext context) + { + return (TService)context.GetService(typeof(TService)); + } + + public static object GetService(this MapContext context, Type type) { var sp = (IServiceProvider) context?.Parameters.GetValueOrDefault(ServiceMapper.DI_KEY); if (sp == null) throw new InvalidOperationException("Mapping must be called using ServiceAdapter"); - return (TService)sp.GetService(typeof(TService)); + return sp.GetService(type); } } }