c# - 微软依赖注入(inject)文档

标签 c# dependency-injection .net-core

在依赖注入(inject)的文档中,我注意到以下行。

The MVC framework will automatically look at the service provider to register our dependency in the Controller.

然后他们提供了一个构造函数注入(inject)的基本示例,不是他们的示例,而是本质上的示例。

public class Example
{
     private IFooFactory foo;

     public Example(IFooFactory foo) => this.foo = foo;

     public void SampleUse()
     {
          using(var context = foo.Create())
              context.DoSomething();
     }
}

如果您有一个控制台应用程序,默认情况下它不会查看服务提供者来注册您对具体实现的依赖项。有没有办法模拟一下?否则,控制台应用程序将要求您执行以下操作:

public static Main(string[] args)
{
    // Stuff to prepare the application and build service provider.
    var service = serviceProvider.GetService<IFooFactory>();
    using(var context = service.Create())
        context.DoSomething();

    // OR

    var fooFactory = serviceProvider.GetService<IFooFactory>();
    new Example(fooFactory).SampleUse();
}

这会产生必须传递 IFooFactory 或将您可能希望分离结构的内容拉入主干的问题。当使用定义的接口(interface)创建新类时,如何使控制台应用程序查看提供程序?

最佳答案

您必须手动创建所有内容,因为框架无法自动为您完成这些操作。

var services = new ServiceCollection();
services.AddTransient<IFooFactory, FooFactory>();
services.AddTransient<Example>();

IServiceProvider serviceProvider = services.BuildServiceProvider();

Example example = serviceProvider.GetService<Example>();

example.SampleUse();

虽然并不理想,但通常是大多数手动配置 DI 的示例中所示的方式。

当您检查框架 DI 集成时,它会在启动期间在幕后执行完全相同的操作。

您可能可以编写自己的代码来检查可用类型,但这是一项需要您自己解决的非常广泛的任务。

引用Dependency injection in ASP.NET Core

Default service container replacement

The built-in service container is meant to serve the needs of the framework and most consumer apps. We recommend using the built-in container unless you need a specific feature that it doesn't support. Some of the features supported in 3rd party containers not found in the built-in container:

  • Property injection
  • Injection based on name
  • Child containers
  • Custom lifetime management
  • Func<T> support for lazy initialization

关于c# - 微软依赖注入(inject)文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52743599/

相关文章:

c# - aws codebuild dotnet :5. 0 - 没有可用的 sdk 命令

c# - 按名称属性比较文本框控件

c# - 如何分割这个字符串并识别最后一个 '*' 之后的第一个句子?

android-studio - 在 Dagger2 中查找提供者的便捷方式

vue.js - 如何解决无法导入模块 '@nuxt/builder' ?

c# - 似乎无法编写通用的读写

java - Guice:如何在没有注入(inject)器或使用构造函数注入(inject)的情况下获取单例实例

java - 这是在 guice 中使用自定义注释的正确方法吗?

azure - 如何在 Azure Durable Functions 中使用依赖注入(inject)?

javascript - 如果密码和确认密码不同,如何拒绝 Controller 操作?