注册asp.net core webapi中未直接引用的Class Libarary的依赖

问题描述 投票:0回答:1

我有一个带有libaraies类的asp.net core web api项目。我可以注册类 libaray 的依赖关系,这些依赖关系直接作为引用添加到 asp.net core webapi 项目中。但我无法找到方法来注册未直接添加到 webapi 项目的类库的依赖项。

例如,正如您在下面的屏幕截图中看到的,

1.这是Asp.net core webapi项目。 2.它有类库FirstClasslib项目。 3.添加FirstClasslib项目作为对Asp.net core webapi项目的引用。 4.FirstClasslib项目有SecondClasslib项目的dll引用。 5.SecondClasslib也是一个具有接口及其实现的库,如下图所示

我想通过 DI 注册 SecondClasslib 的依赖关系,就像我为 FirstClasslib 所做的那样。但由于它没有直接链接到 Asp.Net Web API 项目,我该怎么做?

请查找源代码存储库,https://github.com/sujadkar/WebApplication1

我尝试过 BuildServiceProvider 方法,但很多人说这是反模式,我们应该避免。我想使用依赖注入来解决 SecondClasslib 的依赖关系。

c# .net-core dependency-injection asp.net-core-webapi class-library
1个回答
0
投票

如果您不希望您的 api 项目添加对 SecondClassLib 的引用,请在您的 FirstClassLib 项目中

创建扩展方法:

public static class MyExtension
{
    public static IServiceCollection AddSecondClassLibServices(this IServiceCollection services)
    {
        // regist all services here
        services.AddScoped<ISecondClass, SecondClassImplementation>();
        return services;
    }
}

在您的 WebApi 项目中:

builder.Services.AddSecondClassLibServices();
© www.soinside.com 2019 - 2024. All rights reserved.