Skip to content

Instantly share code, notes, and snippets.

@JohanLarsson
Created November 26, 2016 19:09
Show Gist options
  • Save JohanLarsson/72c10ada48f82dc781a2755c84c7307b to your computer and use it in GitHub Desktop.
Save JohanLarsson/72c10ada48f82dc781a2755c84c7307b to your computer and use it in GitHub Desktop.
/// <summary>
/// Allows using <see cref="IInject{T}"/> and explicit implementation of interfacemethods with [Inject]
/// </summary>
public class CustomKernel : StandardKernel
{
public CustomKernel(INinjectSettings settings, params INinjectModule[] modules)
: base(settings, modules)
{
}
protected override void AddComponents()
{
base.AddComponents();
Components.Remove<ISelector, Selector>();
Components.Add<ISelector, IInjectSelector>();
}
private class IInjectSelector : Selector
{
public IInjectSelector([NotNull] IConstructorScorer constructorScorer, [NotNull] IEnumerable<IInjectionHeuristic> injectionHeuristics)
: base(constructorScorer, injectionHeuristics)
{
}
/// <summary>
/// Allows for:
/// 1) Explicit implementation of methods with [Inject] attribute
/// 2) Implementing <see cref="IInject{T}"/>
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public override IEnumerable<MethodInfo> SelectMethodsForInjection(Type type)
{
return base.SelectMethodsForInjection(type)
.Concat(type.GetInterfaces()
.SelectMany(i => i.GetMethods().Where(m => m.IsDefined(typeof(InjectAttribute), true))))
.Concat(type.GetInterfaces()
.Where(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IInject<>))
.Select(type.GetInterfaceMap)
.SelectMany(im => im.InterfaceMethods));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment