Skip to content

Instantly share code, notes, and snippets.

@nojaf
Created May 3, 2016 14:35
Show Gist options
  • Save nojaf/a3f1c3fd2d8b924e64348d425c2e9285 to your computer and use it in GitHub Desktop.
Save nojaf/a3f1c3fd2d8b924e64348d425c2e9285 to your computer and use it in GitHub Desktop.
Unity config with Mediatr
using System;
using System.Linq;
using System.Reflection;
using MediatR;
using Microsoft.Practices.Unity;
namespace Project.Infrastructure
{
public static class UnityConfiguration
{
static UnityConfiguration()
{
Container = new UnityContainer();
Container.RegisterType<IMediator, Mediator>();
Container.RegisterInstance<SingleInstanceFactory>(t => Container.Resolve(t));
Container.RegisterInstance<MultiInstanceFactory>(t => Container.ResolveAll(t));
var requestHandlerType = typeof(IRequestHandler<,>);
var handlers =
Assembly.GetExecutingAssembly().GetTypes().Where(t => t.GetInterfaces().Any(i => IsSubclassOfRawGeneric(requestHandlerType,i)));
foreach (var handler in handlers)
{
var interfaces = handler.GetInterfaces();
foreach (var @interface in interfaces)
{
Container.RegisterType(@interface, handler);
}
}
}
static bool IsSubclassOfRawGeneric(Type generic, Type toCheck)
{
while (toCheck != null && toCheck != typeof(object))
{
var currentType = toCheck.IsGenericType ? toCheck.GetGenericTypeDefinition() : toCheck;
if (generic == currentType)
{
return true;
}
toCheck = toCheck.BaseType;
}
return false;
}
public static IUnityContainer Container { get; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment