我有一个界面IInterface
,以及两个imeplmentations Impl1
和Impl2
。
每个实现都使用KeyAttribute
注释:
[Key("key1")]
public class Impl1 : IInterface {}
[Key("key2")]
public class Impl2 : IInterface {}
Impl1
位于汇编中,Impl2
位于另一个汇编中。
按惯例创建绑定:
this.Bind(b => b.FromAssembliesMatching("*")
.SelectAllClasses()
.InheritedFrom(typeof(IInterface))
.BindAllInterfaces()
);
通过配置,我的项目的配置类似于<user, backend>
列表,其中backend
是与之关联的后端密钥。
当我加载用户配置时,我需要Get
与implementation.KeyAttribute.Equals(currentUser)
相关联的实现。
有什么想法吗?
答案 0 :(得分: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;
}
}