I have an object whose constructor requires a primitive. I register it using a delegate (please excuse the contrived example).
container.Register<Account>(() => new Account(1000M), Lifestyle.Singleton);
I register this type Account
as the implementation of an interface IAccount
. When doing so using the call marked B
below, SimpleInjector's .Verify()
complains:
/* 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')
Using the call marked A
instead has no such issues and works as intended:
/* A */container.Register<IAccount>(() => container.GetInstance<Account>(), Lifestyle.Singleton);
I seem to have incorrectly assumed that A
and B
would be effectively equivalent. What have I missed? Why does B
fail to utilise the registered delegate for creation of the Account
instance? Thank you.
(File below is LINQPad (.linq) format)
<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; }
}
Account
here is a service; the example is contrived just for brevity/simplicity. I have done a little research (saw your #246 issue in the SimpleInjector repo on GitHub) and have seen that the primitive ctor param can be solved in a few ways, and that while generally delegates should be avoided, they can be used in this scenario. I think I understand the complaint of .Verify() under normal circumstances; I just don't understand it here when I have told SimpleInjector how to instantiate the type in question, especially because the other .Register() invocation works.funds
, the ctor param, represents a value which initialises a quantity in the object that changes during runtime; put differently,funds
itself does not change, but the quantity it initialises does. This differs from the code sample in the question (again for brevity).