等效的简单注入器 .Register 调用

Equivalent Simple Injector .Register invocations

我有一个对象,其构造函数需要基元。我使用委托注册它(请原谅人为的例子)。

container.Register<Account>(() => new Account(1000M), Lifestyle.Singleton);

我将此类型 Account 注册为接口 IAccount 的实现。当使用下面标记为 B 的调用这样做时,SimpleInjector 的 .Verify() 抱怨:

/* B */container.Register<IAccount, Account>(Lifestyle.Singleton);

The constructor of type Account contains parameter 'funds' of type decimal, which can not be used for constructor injection because it is a value type. (Parameter 'TImplementation')

使用标记为 A 的调用没有此类问题并且按预期工作:

/* A */container.Register<IAccount>(() => container.GetInstance<Account>(), Lifestyle.Singleton);

我似乎错误地认为 AB 有效地 等效。我错过了什么?为什么 B 无法利用已注册的委托来创建 Account 实例?谢谢。

(以下文件为 LINQPad (.linq) 格式)

<Query Kind="Program">
  <NuGetReference>SimpleInjector</NuGetReference>
  <Namespace>SimpleInjector</Namespace>
</Query>

void Main()
{
    var containerRegistry = new ContainerRegistry();
    Console.WriteLine("Balance = " + containerRegistry.GetInstance<Account>().Balance);
}

public class ContainerRegistry
{
    private readonly Container container = new Container();

    public ContainerRegistry()
    {
        container.Register<Account>(() => new Account(1000M), Lifestyle.Singleton);

        /* A */container.Register<IAccount>(() => container.GetInstance<Account>(), Lifestyle.Singleton);
        /* B */container.Register<IAccount, Account>(Lifestyle.Singleton);

        container.Verify();
    }
    
    [Obsolete] public TInstanceType GetInstance<TInstanceType>() where TInstanceType : class
        => container.GetInstance<TInstanceType>();
}

public class Account : IAccount
{
    public decimal Balance => funds;
    
    private readonly decimal funds;
    
    public Account(decimal funds)
    {
        this.funds = funds;
    }
}

public interface IAccount
{
    decimal Balance { get; }
}

试试这个:

container.Register<IAccount>(
    () => new Account(1000M),
    Lifestyle.Singleton);

Register<T, R>() 的调用始终应用自动装配(按设计),这意味着 R 是由容器通过调用其构造函数创建的。因此,它将不会重用委托的重载。这被认为是不同的注册。这就是 API 的工作原理。