DI .Net Core MVC 1.0

bil*_*por 2 c# asp.net-mvc dependency-injection

我在许多MVC示例中看到如何ConfigurationServicesStartupClass 的方法中注册接口.当您的代码全部写在MVC应用程序中时,这很好,但在"真实世界"中,情况不一定如此.

我在表单中有一个类库项目

public class MyService : IMyService
{
    private readonly IMyRepository _myRepository;
    public MyService(IMyRepository myRepository)
    {
        _myRepository = myRepository;
    }
    .......
Run Code Online (Sandbox Code Playgroud)

现在在我的控制器中我有一个形式的构造函数:

public HomeController(IConfigurationRoot config, IMyServcie myService)
{
    ......
Run Code Online (Sandbox Code Playgroud)

问题是,MyService接口还没有在DI容器中注册,我真的不想ConfigurationServicesservices.AddScoped<interface,class>()我的其他层的代码行填充方法.

我需要在其他层(存储库和服务)中首先在这里注册它们(两者都是.NET Core类库项目),然后将这些容器连接到父容器中?

Nko*_*osi 5

ConfigurationServices是你的作品根,所以你在那里注册你的服务.膨胀必须到某个地方.您可以在其他图层和目标中创建扩展方法IServiceCollection,然后根据需要进行填充.他们在技术上并没有首先在那里注册.当您应用扩展方法时,它们在组合根中注册IServiceColection

您必须引用其他图层Microsoft.Extensions.DependencyInjection.Abstractions才能访问该IServiceCollection界面.

IMO我不认为这些扩展方法需要在您的服务或存储库层中.这些层不需要知道它们是如何组成的.您可以轻松地将它们放在另一个类的组合根中,如上所示,如果最终目标是使启动类更清晰,则可以调用它们.或者放入一个单独的扩展项目,专门用于定位.net核心的DI框架.

服务扩展层

public static IServiceCollection AddMyServices(this IServiceCollection services) {
    services.AddScoped<IMyService, MyService>();
    //...add other services
}
Run Code Online (Sandbox Code Playgroud)

存储库扩展层

public static IServiceCollection AddMyRepositories(this IServiceCollection services) {
    services.AddScoped<IMyRepository, MyRepository >();
    //...add other services
}
Run Code Online (Sandbox Code Playgroud)

然后在你的作文根 ConfigureServices

public void ConfigureServices(IServiceCollection services) {
    //...other code

    services
        .AddMyServices()
        .AddMyRepositories();

    //...other code
}
Run Code Online (Sandbox Code Playgroud)

基于注释更新,你可以很容易地调用services.AddMyRepositories()AddMyServies扩展方法,而不是主要的项目本身

public static IServiceCollection AddMyServices(this IServiceCollection services) {
    services.AddMyRepositories();
    services.AddScoped<IMyService, MyService>();
    //...add other services
}
Run Code Online (Sandbox Code Playgroud)

然后在你的作文根目录中,ConfigureServices只需要调用AddMyServices

public void ConfigureServices(IServiceCollection services) {
    //...other code

    services.AddMyServices();

    //...other code
}
Run Code Online (Sandbox Code Playgroud)