Skip to content

Instantly share code, notes, and snippets.

@dannyc02
Created February 18, 2016 15:51
Show Gist options
  • Save dannyc02/6d42b90154d8478dc6fd to your computer and use it in GitHub Desktop.
Save dannyc02/6d42b90154d8478dc6fd to your computer and use it in GitHub Desktop.
CQRS - generic handlers
using FluentAssertions;
using MediatR;
using NUnit.Framework;
using StructureMap.Graph;
using System;
using System.IO;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using StructureMap;
using StructureMap.Graph.Scanning;
using Container = StructureMap.Container;
namespace MediatorTests
{
[TestFixture]
public class UnitTest1
{
public class HomeItem : IItem
{
}
[Test]
public void ShouldResolveGenericHandler()
{
var container = new Container(cfg =>
{
cfg.Scan(scanner =>
{
scanner.TheCallingAssembly();
scanner.IncludeNamespaceContainingType<HomeItem>();
scanner.AddAllTypesOf(typeof(IRequestHandler<,>));
scanner.With(new AddRequestHandlersWithGenericParametersToRegistry());
scanner.WithDefaultConventions();
});
cfg.For<SingleInstanceFactory>().Use<SingleInstanceFactory>(ctx => t => ctx.GetInstance(t));
cfg.For<MultiInstanceFactory>().Use<MultiInstanceFactory>(ctx => t => ctx.GetAllInstances(t));
cfg.For<IMediator>().Use<Mediator>();
});
var mediator = container.GetInstance<IMediator>();
Console.Write(container.WhatDoIHave());
var response = mediator.Send(new CreateItemCommand<HomeItem>());
response.Should().NotBeNull();
}
}
public class CreateItemCommand<T> : IRequest<T> where T: IItem
{
}
public class CreateItemCommandHandler<T> : IRequestHandler<CreateItemCommand<T>, T> where T : IItem
{
public T Handle(CreateItemCommand<T> message)
{
return Activator.CreateInstance<T>();
}
}
public class AddRequestHandlersWithGenericParametersToRegistry : IRegistrationConvention
{
public void ScanTypes(TypeSet types, Registry registry)
{
foreach (var concreteClass in types.FindTypes(TypeClassification.Concretes))
{
if (concreteClass.GetInterfaces().Contains(typeof(IItem)))
{
var genericCommand = typeof (CreateItemCommand<>).MakeGenericType(concreteClass);
var interfaceHandlerType = typeof(IRequestHandler<,>).MakeGenericType(genericCommand, concreteClass);
var concreteHandlerType = typeof(CreateItemCommandHandler<>).MakeGenericType(concreteClass);
registry.For(interfaceHandlerType).Use(concreteHandlerType);
}
}
}
}
public interface IItem
{
}
}
@dannyc02
Copy link
Author

TODO: currently only adds commands that implement CreateItemCommand - would be better if this found any commands that take a type of

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment