Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save robvanpamel/2aa2b27da8d0f922b9b98b6331b2e57f to your computer and use it in GitHub Desktop.
Save robvanpamel/2aa2b27da8d0f922b9b98b6331b2e57f to your computer and use it in GitHub Desktop.
AutoFac Resolving Generic Factory
using System;
using System.Collections.Generic;
using Xunit;
using Autofac;
namespace Tests
{
public class Tests
{
public class ClassUnderTest
{
public IContainer CreateContainer()
{
var builder = new Autofac.ContainerBuilder();
builder.RegisterType<MyCommandHandler>().As<ICommandHandler<AnotherCommand>>();
builder.RegisterType<MyCommandHandler>().As<ICommandHandler<MyCommand>>();
builder.RegisterGeneric(typeof(CompositeCommandHandler<>)).As(typeof(ICommandHandler<>));
// How to register this ???
// builder.Register<Func<ICommand, ICommandHandler<ICommand>>>(c => s => c.Resolve(typeof(s)));
return builder.Build();
}
}
[Fact]
public void Test1()
{
// arrange
var myClassUnderTest = new ClassUnderTest();
var container = myClassUnderTest.CreateContainer();
var myCommand = new MyCompositeCommand(new List<ICommand> { new MyCommand(), new AnotherCommand() });
// act
Assert.IsType<MyCommandHandler>(container.Resolve<ICommandHandler<MyCommand>>());
Assert.IsType<MyCommandHandler>(container.Resolve<ICommandHandler<AnotherCommand>>());
var handler = container.Resolve<ICommandHandler<MyCompositeCommand>>();
handler.Handle(myCommand);
}
public interface ICommand { }
public interface ICompositeCommand : ICommand
{
IEnumerable<ICommand> Commands { get; }
}
public class MyCommand : ICommand { }
public class AnotherCommand : ICommand { }
public class MyCompositeCommand : ICompositeCommand
{
private readonly IEnumerable<ICommand> commands;
public MyCompositeCommand(IEnumerable<ICommand> commands)
{
this.commands = commands;
}
public IEnumerable<ICommand> Commands { get { return commands; } }
}
public interface ICommandHandler<T> where T : ICommand
{
void Handle(T command);
}
public class MyCommandHandler : ICommandHandler<MyCommand>, ICommandHandler<AnotherCommand>
{
public void Handle(MyCommand command)
{
Console.WriteLine("Handling MyCommand");
}
public void Handle(AnotherCommand command)
{
Console.WriteLine("Handling AnotherCommand");
}
}
public class CompositeCommandHandler<CompositeCommand> : ICommandHandler<CompositeCommand> where CompositeCommand : ICompositeCommand
{
private Func<ICommand, ICommandHandler<ICommand>> _factory;
public CompositeCommandHandler(Func<ICommand, ICommandHandler<ICommand>> factory)
{
_factory = factory;
}
public void Handle(CompositeCommand command)
{
foreach (var myCommand in command.Commands)
{
var handler = _factory(myCommand);
handler.Handle(myCommand);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment