在 asp net core 中扩展 IServiceCollection

den*_*orf 2 asp.net-core-mvc asp.net-core

我想创建一个类库项目,并在该项目中包含一些实现这些接口的接口和类。

之后,我想提供这个类库项目,作为 nuget 包,因此,从 IServiceCollection 获得某种扩展将是理想的,以便在 nuget 安装后Startup.csConfigureServices()在应用程序中使用一行代码正在使用 nuget,做这样的事情:

services.AddServicesFromMyNugetPackage()

并且该方法将根据IServiceCollection方法执行,我的 DI 配置。

任何的想法?

Get*_*ela 5

在您的库中,您可以创建一个静态类并编写一些扩展方法,您可以在其中注册您的依赖项,如下例所示:

public static class ServicesExtensions
{
        public static void AddMyLibraryServices(this IServiceCollection services)
        {
            // register your services here
        }
 }
Run Code Online (Sandbox Code Playgroud)

然后在您的启动文件中:

services.AddMyLibraryServices();
Run Code Online (Sandbox Code Playgroud)

  • 是的,你可以这么做。我建议传递自定义配置类而不是整个配置。 (2认同)