【问题标题】:How to export interfaces with Asp.Net Core Dependency injection如何使用 Asp.Net Core Dependency injection 导出接口
【发布时间】:2016-08-21 19:20:50
【问题描述】:

在 MEF 中,我可以使用以下代码导出通用接口:

registration.ForTypesMatching(t => t.GetInterface(typeof(ICommandHandler<>).Name) != null)
    .ExportInterfaces().SetCreationPolicy(CreationPolicy.NonShared);

如何在 Asp.Net Core 中配置服务以实现相同的功能,即仅通过接口注册服务类?

【问题讨论】:

    标签: dependency-injection asp.net-core


    【解决方案1】:

    在 ASP.NET Core 应用程序中,您可以通过扩展 Startup.ConfigureServices 方法在 Startup.cs 中配置服务。 IServiceCollection 实例的 services 参数允许您添加自己的服务来实现接口。

    Startup.cs

    public void ConfigureServices(IServiceCollection services)
    {
        // setup of ASP.NET Services like MVC
        ...
    
        services.AddSingleton<IMyInterface>(objectImplementingMyInterface);
        services.AddTransient<IAnotherInterface, SomeAnotherInterfaceImplementer>();
    
    }
    

    如果内置的 DI 容器 (https://docs.asp.net/en/latest/fundamentals/dependency-injection.html) 的基本功能不能满足您的要求,那么也可以合并其他 DI 容器库。一个例子是 Autofac (http://docs.autofac.org/en/latest/integration/aspnetcore.html)。 ASP.NET 团队目前正在努力进行更改,以使 DI 库维护者更容易集成到 ASP.NET Core。

    【讨论】:

    • 在 ASP.NET Core 中集成任何容器总是很容易,正如 here 所解释的那样。
    【解决方案2】:

    ASP.NET Core 提供了自己的 Inversion of Control 容器,由 IServiceProvider 接口表示。 有关基本用法以及如何注册自己的课程,请查看此页面:https://docs.asp.net/en/latest/fundamentals/dependency-injection.html#

    【讨论】:

      猜你喜欢
      • 2021-08-03
      • 2017-08-14
      • 1970-01-01
      • 1970-01-01
      • 2018-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多