Microsoft.Toolkit.Mvvm.DependencyInjection.Ioc

比较GetService()和GetRequiredService()

请使用使用 GetRequiredService()

  1. GetService()返回一个serviceType类型的服务对象。如果返回的是一个没有类型的服务对象serviceType则返回null。
  2. GetRequiredService()返回一个serviceType类型的服务对象。如果没有serviceType类型的服务,则抛出一个InvalidOperationException异常。

依赖关系注入原则

  1. 依赖关系是.NET框架的内置部分。
  2. 使用接口或基类将依赖关系实现抽象化
  3. 在服务容器中注册依赖类。.NET提供内置服务容器IServiceProvider。服务通常在程序启动时注册,并追加到IServiceCollection。添加所有服务后,使用BuildServiceProvider创建服务容器。
  4. 将服务注入到使用它的类的构造函数。框架负责创建依赖关系的实例,并在不需要时将其释放。

IServiceProvider & ServiceCollection

Autofac

  • Structure your app with inversion of control (IoC) in mind.
  • Add Autofac references.
  • At application startup…
    • Create a ContainerBuilder.
    • Register components.
    • Build the container and store it for later use.
  • During application execution…
    • Create a lifetime scope from the container.
    • Use the lifetime scope to resolve instances of the components.

Code Example

public class Program
{
    private static IContainer Container { get; set; }

    static void Main(string[] args)
    {
    var builder = new ContainerBuilder();
    builder.RegisterType<ConsoleOutput>().As<IOutput>();
    builder.RegisterType<TodayWriter>().As<IDateWriter>();
    Container = builder.Build();

    // The WriteDate method is where we'll make use
    // of our dependency injection. We'll define that
    // in a bit.
    WriteDate();
    }
}

Register

// Register types that expose interfaces...
builder.RegisterType<ConsoleLogger>().As<ILogger>();

// Register instances of objects you create...
var output = new StringWriter();
builder.RegisterInstance(output).As<TextWriter>();

// Register expressions that execute to create objects...
builder.Register(c => new ConfigReader("mysection")).As<IConfigReader>();