2016-03-17 2 views
0

У меня есть интерфейс IInterface и два изображенияи Impl2.Контекстуализированные привязки с NInject

Каждая реализация помечается с KeyAttribute:

[Key("key1")] 
public class Impl1 : IInterface {} 

[Key("key2")] 
public class Impl2 : IInterface {} 

Impl1 находится в сборке и Impl2 в другой.

Im создания привязки по соглашению:

this.Bind(b => b.FromAssembliesMatching("*") 
      .SelectAllClasses() 
      .InheritedFrom(typeof(IInterface)) 
      .BindAllInterfaces() 
     ); 

По конфигурации, мой проект имеет конфигурацию, как список <user, backend>, где backend является ключевым бэкенд будет ассоциироваться с.

Когда я загружаю конфигурацию пользователей, мне нужно, чтобы Get реализована реализация, где implementation.KeyAttribute.Equals(currentUser).

Любые идеи?

ответ

1

Вы можете использовать метод Configure создать поименованые:

kernel.Bind(x => x 
    .FromThisAssembly() 
    .SelectAllClasses() 
    .InheritedFrom<IInterface>() 
    .BindAllInterfaces() 
    .Configure((syntax, type) => syntax.Named(GetKeyFrom(type)))); 

private static string GetKeyFrom(Type type) 
{ 
    return type 
     .GetCustomAttributes(typeof(KeyAttribute), false) 
     .OfType<KeyAttribute>() 
     .Single() 
     .Key; 
} 

затем решить его:

kernel.Get<IInterface>("key1"); 
kernel.Get<IInterface>("key2"); 

Вот весь мой код (для целей проверки):

using System; 
using System.Linq; 
using FluentAssertions; 
using Ninject; 
using Ninject.Extensions.Conventions; 
using Xunit; 

[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] 
public class KeyAttribute : Attribute 
{ 
    public KeyAttribute(string key) 
    { 
     Key = key; 
    } 

    public string Key { get; private set; } 
} 

public interface IInterface { } 

[Key("key1")] 
public class Impl1 : IInterface { } 

[Key("key2")] 
public class Impl2 : IInterface { } 

public class Test 
{ 
    [Fact] 
    public void Foo() 
    { 
     var kernel = new StandardKernel(); 
     kernel.Bind(x => x 
      .FromThisAssembly() 
      .SelectAllClasses() 
      .InheritedFrom<IInterface>() 
      .BindAllInterfaces() 
      .Configure((syntax, type) => syntax.Named(GetKeyFrom(type)))); 

     kernel.Get<IInterface>("key1").Should().BeOfType<Impl1>(); 
     kernel.Get<IInterface>("key2").Should().BeOfType<Impl2>(); 
    } 

    private static string GetKeyFrom(Type type) 
    { 
     return type 
      .GetCustomAttributes(typeof(KeyAttribute), false) 
      .OfType<KeyAttribute>() 
      .Single() 
      .Key; 
    } 
}