与NInject的上下文绑定

时间:2016-03-17 12:37:48

标签: c# ninject

我有一个界面IInterface,以及两个imeplmentations Impl1Impl2

每个实现都使用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是与之关联的后端密钥。

当我加载用户配置时,我需要Getimplementation.KeyAttribute.Equals(currentUser)相关联的实现。

有什么想法吗?

1 个答案:

答案 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;
    }
}