Skip to content

Instantly share code, notes, and snippets.

@vegar
Last active May 10, 2017 12:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vegar/b42f347907d326fbae83f6bf55156282 to your computer and use it in GitHub Desktop.
Save vegar/b42f347907d326fbae83f6bf55156282 to your computer and use it in GitHub Desktop.
LightInject issue #359
using System;
using System.Linq;
using ConsoleApplication3.LightInject;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
var container = new ServiceContainer();
container.Register(typeof(IMyInterface<>), typeof(MyGenericImplementation<>));
container.Register<IMyInterface<string>, MyImplementation>();
//container.RegisterAssembly(Assembly.GetExecutingAssembly(), (serviceType, implementationType) => serviceType.IsSubclassOfRawGeneric(typeof(IMyInterface<>)));
var services = container.AvailableServices.Select(s => $"{s.ServiceType} - {s.ImplementingType}");
Console.WriteLine(string.Join("\n\r", services));
var strImp = container.GetInstance<IMyInterface<string>>();
Console.WriteLine($"GetInstance<IMyInterface<string>>: {strImp.GetType().Name}");
Console.ReadKey();
}
}
interface IMyInterface<T> { }
class MyGenericImplementation<T> : IMyInterface<T> { }
class MyImplementation: IMyInterface<string> { }
public static class TypeExtentions
{
// Slightly modified code from http://stackoverflow.com/a/457708/11956
public static bool IsSubclassOfRawGeneric(this Type toCheck, Type generic)
{
while (toCheck != null && toCheck != typeof(object))
{
var cur = toCheck.IsGenericType ? toCheck.GetGenericTypeDefinition() : toCheck;
if (generic == cur)
{
return true;
}
toCheck = toCheck.BaseType;
}
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment