前言:本人小白一个,写博客只为自己记住一些知识要点,有不对的地方请大佬多多指教。
在用类库构建nuget包时,为了方便在应用层注册,通常会写一个扩展方法来进行注册,以免在应用层进行多次注册。
- 首先需要创建一个静态类,例如xxxxExtentions.cs
- 其次在类添加一个方法,返回值为void 列如AddServices(),方法中需要添加参数 参数为 this IServiceCollection services,也就是ConfigureServices方法中的参数,这个方法其实也就是 IServiceCollection 的扩展方法。
- 然后就是在其中注册你添加的一些服务或者引用的nuget包中的注册服务。
- 最后就是在应用层的ConfigureServices中调用你写这个方法即可,也就是 service.AddServices();
- 代码如下:
-
public static class XXXExtentions { public static void AddServices(this IServiceCollection services) { //注册服务 services.AddHttpContextAccessor(); //注册自己写某些的接口 services.AddSingleton<ITestService, TestService>(); } } startUp.cs // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { //应用层中调用该注册方法,就不用再一个服务一个服务去注册了 services.AddServices(); services.AddControllersWithViews(); }