AspNetCore项目-Service注入或覆盖

本文介绍了一种在ASP.NET Core应用中不修改代码即可灵活切换已注册服务的方法。通过扩展和服务注册,实现在不同环境下无缝更换服务提供者,如从网易云音乐切换到QQ音乐播放周杰伦歌曲,避免重复代码更新。

  使用AspNetCore开发的都已经尝到了各种花式注入的甜头,其中最基本的注入方式莫过于IServiceCollection.Add[Scoped/Transient/Singleton]<TService,TImplementation>()了。而对于已经注册的Service,如果有临时更换的需求就会稍显麻烦。

拿一个事例做说明:比如以前你是使用网易云音乐听周杰伦的歌的,当网易云不再拥有周杰伦音乐授权的时候,你不得不开始使用QQ音乐来听周杰伦的歌,因为现在QQ音乐拥有了版权。这时候你就需要想办法怎么替换音乐播放器了。

  这个问题我们可以抽象一下:

  音乐播放器作为一个接口:IMusicPlayer,该接口拥有一个方法:PlayJayChou,而最初只是网易云音乐(NetEaseCloudMusic)继承并实现了该接口,且在你的正式环境中使用着,例如AddScoped<IMusicPlayer,NetEaseCloudMusic>()。

  此时需要更换为QQ音乐了,按照一般做法是,OK,添加QQMusic,继承并实现IMusicPlayer,然后嗯,将代码替换:AddScoped<IMusicPlayer,QQMusic>(),发布上线;

  试想,如果QQ版权也过了,最后百度音乐拥有了版权,你还想这样改一遍代码,再发布上线吗?

 

  基于此,我写了一个小小的项目,基于扩展和配置,灵活的切换你的Service。该项目的能力就是在不需要修改主程序代码的情况下,添加扩展并修改配置,完成Service的切换。

  干货:

  先来个项目一览吧,只看src其实可以得知,项目代码量真的很小,我估计不超过250行:

 

  配置:在appsettings.json中配置如下内容,属性意义截图中已经给出注释,数组形式。

  上图配置的映射类:

  

 

  主要的实现思路是,读取配置(IMusicPlayer、QQMusic、QQMusic所在程序集的相对路径),利用反射技术分别获取Service的接口和实现类型。

  获取到serviceType和ImplementationType,离注入还会远吗?

 

 

  如此,项目便已实现。

  使用示例,Startup类的ConfigureServices方法中添加services.AddServiceRegister(),需要放在各类service的注册代码段落之后:

 

  仓库地址:https://github.com/Med1tator/Medit.AspNetCore.ServiceRegister 

  该项目中已包含MusicPlayer的Sample。

 

转载于:https://www.cnblogs.com/Med1tator/p/10322737.html

warn: Microsoft.AspNetCore.HttpsPolicy.HttpsRedirectionMiddleware[3] 4月 01 04:13:32 master dotnet-webapi[5915]: Failed to determine the https port for redirect. 4月 01 04:13:32 master dotnet-webapi[5915]: fail: Microsoft.AspNetCore.Server.Kestrel[13] 4月 01 04:13:32 master dotnet-webapi[5915]: Connection id "0HNBGI21C4J1B", Request id "0HNBGI21C4J1B:00000001": An unhandled exception was thrown by the application. 4月 01 04:13:32 master dotnet-webapi[5915]: System.ArgumentException: IDX10703: Cannot create a 'Microsoft.IdentityModel.Tokens.SymmetricSecurityKey', key length is zero. 4月 01 04:13:32 master dotnet-webapi[5915]: at Microsoft.IdentityModel.Tokens.SymmetricSecurityKey..ctor(Byte[] key) 4月 01 04:13:32 master dotnet-webapi[5915]: at Program.<>c__DisplayClass0_0.<<Main>$>b__4(JwtBearerOptions options) in /home/gitlab-runner/builds/t3_gsTryE/0/oa/webapilljdev/WebApiLLJ/Program.cs:line 89 4月 01 04:13:32 master dotnet-webapi[5915]: at Microsoft.Extensions.Options.ConfigureNamedOptions`1.Configure(String name, TOptions options) 4月 01 04:13:32 master dotnet-webapi[5915]: at Microsoft.Extensions.Options.OptionsFactory`1.Create(String name) 4月 01 04:13:32 master dotnet-webapi[5915]: at Microsoft.Extensions.Options.OptionsMonitor`1.<>c.<Get>b__10_0(String name, IOptionsFactory`1 factory) 4月 01 04:13:32 master dotnet-webapi[5915]: at Microsoft.Extensions.Options.OptionsCache`1.<>c__DisplayClass3_1`1.<GetOrAdd>b__2() 4月 01 04:13:32 master dotnet-webapi[5915]: at System.Lazy`1.ViaFactory(LazyThreadSafetyMode mode) 4月 01 04:13:32 master dotnet-webapi[5915]: at System.Lazy`1.ExecutionAndPublication(LazyHelper executionAndPublication, Boolean useDefaultConstructor) 4月 01 04:13:32 master dotnet-webapi[5915]: at System.Lazy`1.CreateValue() 4月 01 04:13:32 master dotnet-webapi[5915]: at Microsoft.Extensions.Options.OptionsCache`1.GetOrAdd[TArg](String name, Func`3 createOptions, TArg factoryArgument) 4月 01 04:13:32 master dotnet-webapi[5915]: at Microsoft.Extensions.Options.OptionsMonitor`1.Get(String name) 4月 01 04:13:32 master dotnet-webapi[5915]: at Microsoft.AspNetCore.Authentication.AuthenticationHandler`1.InitializeAsync(AuthenticationScheme scheme, HttpContext context) 4月 01 04:13:32 master dotnet-webapi[5915]: at Microsoft.AspNetCore.Authentication.AuthenticationHandlerProvider.GetHandlerAsync(HttpContext context, String authenticationScheme) 4月 01 04:13:32 master dotnet-webapi[5915]: at Microsoft.AspNetCore.Authentication.AuthenticationService.AuthenticateAsync(HttpContext context, String scheme) 4月 01 04:13:32 master dotnet-webapi[5915]: at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context) 4月 01 04:13:32 master dotnet-webapi[5915]: at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication`1 application) 4月 01 04:13:32 master dotnet-webapi[5915]: info: Microsoft.AspNetCore.Hosting.Diagnostics[2]
04-02
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值