如何在Kotlin中为泛型类型创建DI绑定?

时间:2018-11-21 09:13:01

标签: generics dependency-injection kotlin

我正在尝试找到一个基于Kotlin的依赖项注入系统,该系统将允许我绑定诸如Timezone.setDefault(Timezone.getTimezone("XXX"))之类的通用类型并根据需要解析Foo<T>Foo<Int>等。 / p>

Kodein似乎是最受欢迎的DI框架之一,我已经研究过了,但是看不到它是怎么可能的。 Kodein存储库中的Issue #83对此主题进行了一些讨论。

就我而言,我希望能够执行以下操作:

Foo<String>

在C#中,使用Autofac非常简单。下面的代码段是我想要的C#的有效实现:

import com.atpgroup.testmaster.domain.ExecutableNode
import kotlin.reflect.KClass

annotation class TypeClass
annotation class Instance

/**
 * Represents a catalog of nodes.
 *
 * Factory functions to generate nodes are initially registered to this catalog during setup and used to create
 * instances of nodes.
 */
interface NodeCatalog {
    fun <U : ExecutableNode> resolve(nodeType: KClass<U>, id: String): U
}

/**
 * Simplifies resolution of nodes from a reified context.
 */
inline fun <reified T : ExecutableNode> NodeCatalog.resolve(id: String) = resolve(T::class, id)

/**
 * Dummy implementation of a node catalog.
 */
class DummyNodeCatalog : NodeCatalog {
    override fun <U : ExecutableNode> resolve(nodeType: KClass<U>, id: String): U = TODO("not implemented")
}

/**
 * A type class representing the set of types that can behave like numbers.
 */
@TypeClass
interface Num<T>

// Int and Double both behave like numbers.
@Instance object IntNumInstance : Num<Int>
@Instance object DoubleNumInstance : Num<Double>

/**
 * An executable node that adds two numbers together.
 *
 * @param T the type of the numbers that will be added together
 */
class AddNode<T>(override val id: String, private val N: Num<T>) : ExecutableNode {
    override suspend fun execute() = TODO("not implemented")
}

// Resolve two "add nodes" that operate on different types of numbers.
val catalog = DummyNodeCatalog()
val addInts = catalog.resolve<AddNode<Int>>("integer adder")
val addDoubles = catalog.resolve<AddNode<Double>>("double adder")

输出

using System;
using Autofac;

namespace Experiment
{
    internal class Program
    {
        public static void Main()
        {
            var builder = new ContainerBuilder();

            builder.RegisterType<IntNumInstance>().As<INum<int>>();
            builder.RegisterType<DoubleNumInstance>().As<INum<double>>();
            builder.RegisterGeneric(typeof(Add<>));

            var container = builder.Build();
            var addA = container.Resolve<Add<int>.Factory>()("add integers");
            var addB = container.Resolve<Add<double>.Factory>()("add doubles");
            Console.WriteLine(addA);
            Console.WriteLine(addB);
            Console.ReadLine();
        }
    }

    interface INum<T> {}
    class IntNumInstance : INum<int> {}
    class DoubleNumInstance : INum<double> {}

    class Add<T>
    {
        public delegate Add<T> Factory(string id);

        public Add(string id, INum<T> N)
        {
            Id = id;
            this.N = N;
        }

        public string Id { get; }

        private INum<T> N { get; }

        public override string ToString() => $"Add Node ({Id} - {N})";
    }
}

0 个答案:

没有答案