Skip to content

Instantly share code, notes, and snippets.

@joshrobb
Created September 25, 2014 04:53
Show Gist options
  • Save joshrobb/baeb48487c26a3732ea7 to your computer and use it in GitHub Desktop.
Save joshrobb/baeb48487c26a3732ea7 to your computer and use it in GitHub Desktop.
❤️ Ian
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Autofac;
using Autofac.Features.Indexed;
namespace AutofacStrategyPattern
{
class Program
{
static void Main(string[] args)
{
//Arrange
var container = SetupContainer();
var mpe = container.Resolve<MerchantPaymentExporter>();
var ms = new MemoryStream();
var sw = new StreamWriter(ms);
//Act
mpe.Export(ExportFormat.ACS, sw);
mpe.Export(ExportFormat.Shelby, sw);
//Ass
sw.Flush();
ms.Position = 0;
ms.Seek(0, 0);
var r = new StreamReader(ms);
Console.WriteLine(r.ReadToEnd());
}
static IContainer SetupContainer()
{
var builder = new ContainerBuilder();
RegisterMPW<AcsMerchantPaymentWriter>(builder, ExportFormat.ACS);
RegisterMPW<ShelbyMerchantPaymentWriter>(builder, ExportFormat.Shelby);
builder.RegisterType<MerchantPaymentExporter>();
var container = builder.Build();
return container;
}
static void RegisterMPW<T>(ContainerBuilder builder,ExportFormat format)
{
builder.RegisterType<T>()
.Keyed<IMerchantPaymentWriter>(format)
.AsImplementedInterfaces();
}
}
public class MerchantPaymentExporter
{
readonly IIndex<ExportFormat, IMerchantPaymentWriter> _writers;
public MerchantPaymentExporter(IIndex<ExportFormat,IMerchantPaymentWriter> writers)
{
_writers = writers;
}
public void Export(ExportFormat format, StreamWriter output)
{
var writer = default(IMerchantPaymentWriter);
if (!_writers.TryGetValue(format, out writer)) {
throw new Exception("No writer for: " + format);
}
writer.Write(Enumerable.Empty<object>(),output);
}
}
public interface IMerchantPaymentWriter
{
void Write(IEnumerable<object> payments, StreamWriter writer);
}
public class AcsMerchantPaymentWriter : IMerchantPaymentWriter
{
public void Write(IEnumerable<object> payments, StreamWriter writer)
{
writer.Write("ACS");
}
}
public class ShelbyMerchantPaymentWriter : IMerchantPaymentWriter
{
public void Write(IEnumerable<object> payments, StreamWriter writer)
{
writer.Write("Shelby");
}
}
public enum ExportFormat
{
None,
Arena,
ACS,
Shelby
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment