Ninject按惯例使用BindToFactory绑定到具有类T的工厂接口

时间:2013-03-04 15:31:24

标签: ninject factory ninject-extensions

我想替换此代码:

Kernel.Bind<ITaskFactory<AlertTask>>().ToFactory();
Kernel.Bind<ITaskFactory<PopupTask>>().ToFactory();

有这样的事情:

Kernel.Bind(scanner => scanner.FromThisAssembly().SelectAllClasses()
   .EndingWith("Task").MAGICGOESHERE().BindToFactory()

我试图创建一个IBindingGenerator,但在尝试获取ITaskFactory&lt; T&gt;时陷入困境。来自T。

1 个答案:

答案 0 :(得分:6)

请改用:

kernel.Bind(scanner => scanner
    .FromThisAssembly()
    .SelectAllInterfaces()
    .EndingWith("Factory")
    .BindToFactory());

kernel.Bind(scanner => scanner
    .FromThisAssembly()
    .SelectAllClasses()
    .EndingWith("Task"));

var f = kernel.Get<ITaskFactory>();
var task1 = f.CreateTask<AlertTask>();
var task2 = f.CreateTask<PopupTask>();

public class AlertTask {}
public class PopupTask { }
public interface ITaskFactory
{
    T CreateTask<T>();
}