I have a Lazy property in my class:
private Lazy<ISmtpClient> SmtpClient
{
get
{
return new Lazy<ISmtpClient>(() => _objectCreator.Create<ISmtpClient>(), true);
}
}
Also a methode that uses this proptery:
public void SendEmail(MailMessage message)
{
SmtpClient.Value.ServerName = "testServer";
SmtpClient.Value.Port = 25;
SmtpClient.Value.Send(message);
}
But in my SmtpClient, in Send(string message) methode are all the propteries that i initialized in the above SendEmail(MailMessage message) methode, null.
How can i fix this?
Thanks in advance.
You are using
Lazy<T>wrong.When using
Lazy<T>you expose a property of the actual type and you have oneLazy<T>instance. You don’t create a new one every time the property is accessed:Now, the first time the
SmtpClientproperty is accessed, the object creator creates a new instance ofMySmtpClient. This is returned. On subsequent calls, the same instance is returned.The usage would be like this: