public interface IMessageFormatter
{
string FormatMessage(string from, string to, string body);
}
public void SendMessage(string to, string body)
Console.WriteLine("to: {0}\r\nfrom: {1}\r\n\r\n{2}", to, _from, _encoder.Encode(body));
public class DefaultFormatter : IMessageFormatter
public string FormatMessage(string from, string to, string body)
return string.Format("to: {0}\r\nfrom: {1}\r\n\r\n{2}", to, from, body);
public class SecretMessageSender
private readonly IEncoder _encoder;
private readonly string _from;
private IMessageFormatter _formatter = new DefaultFormatter();
public SecretMessageSender(string from, IEncoder encoder)
_from = from;
_encoder = encoder;
public IMessageFormatter Formatter
get { return _formatter; }
set { _formatter = value; }
string encodedBody = _encoder.Encode(body);
Console.WriteLine(_formatter.FormatMessage(_from, to, encodedBody));
public class NVelocityMessageFormatter : IMessageFormatter
private readonly VelocityEngine _velocity;
private readonly Template _template;
public NVelocityMessageFormatter(string templateFile)
_velocity = new VelocityEngine();
ExtendedProperties props = new ExtendedProperties();
_velocity.Init(props);
_template = _velocity.GetTemplate(templateFile);
VelocityContext context = new VelocityContext();
context.Put("from", from);
context.Put("to", to);
context.Put("body", body);
context.Put("today", DateTime.Now);
StringWriter writer = new StringWriter();
_template.Merge(context, writer);
return writer.ToString();
To: $to
From: $from
Sent: $today
----------------------
$body
<configuration>
<configSections>
<section name="castle"
type="Castle.Windsor.Configuration.AppDomain.CastleSectionHandler, Castle.Windsor" />
</configSections>
<castle>
<components>
<component id="encoder.silly"
service="IoC.Tutorials.Part10.IEncoder, IoC.Tutorials.Part10"
type="IoC.Tutorials.Part10.SillyEncoder, IoC.Tutorials.Part10" />
<component id="encoder.null"
type="IoC.Tutorials.Part10.NullEncoder, IoC.Tutorials.Part10" />
<component id="messageSender"
type="IoC.Tutorials.Part10.SecretMessageSender, IoC.Tutorials.Part10">
<parameters>SecretMessageSender
<from>alex@bittercoder.com</from>
<encoder>${encoder.null}</encoder>
</parameters>
</component>
<component id="fancyMessageFormatter"
service="IoC.Tutorials.Part10.IMessageFormatter, IoC.Tutorials.Part10"
type="IoC.Tutorials.Part10.NVelocityMessageFormatter, IoC.Tutorials.Part10">
<parameters>
<templateFile>message.vm</templateFile>
</components>
</castle>
</configuration>
<Formatter>${fancyMessageFormatter}</Formatter>
<component id="defualtMessageFormatter"
type="IoC.Tutorials.Part10.DefaultFormatter, IoC.Tutorials.Part10" />