Last active
May 10, 2017 12:29
-
-
Save vegar/b42f347907d326fbae83f6bf55156282 to your computer and use it in GitHub Desktop.
LightInject issue #359
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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