总结:
所以,我需要:
为了注册我的"插件":
this.Kernel.Bind(b => b.FromAssembliesMatching("*")
.SelectAllClasses()
.InheritedFrom(typeof(Extensibility.IProducerPlugin))
.BindAllInterfaces());
我还没弄清楚如何实现这个目标。
你能帮我吗?
我很感激你的帮助。
答案 0 :(得分:1)
一般的DI容器和特殊的Ninject 不适合在运行时添加和删除容器的新绑定。有些像Autofac,甚至不允许在创建容器后添加绑定。
Ninject允许随时添加新的绑定,但你不能永远删除它们(*来自某些用例Rebind
,但这不一样)。
kernel.Release(object)
没有删除绑定,它只删除对它所拥有的object
的所有引用。
例如:
var foo = new object();
kernel.Bind<object>().ToConstant(foo);
允许foo
垃圾收集,您可以执行以下操作之一:
kernel.Release(foo);
kernel.Dispose(); kernel = null;
这正是kernel.Release(...)
的用途。也许你也可以Release
一个单身人士,从而迫使ninject在下一个请求中创建一个新单身。但我不知道这是否真的有效,如果确实如此,那肯定是一个意想不到的黑客攻击。
所以你应该做的是自己管理列表/字典。您可以使用ninject绑定并注入列表/词典/管理器你称之为的内容,但是你不能让ninject manager成为列表本身。
答案 1 :(得分:0)
我使用这个IBindingGenerator接口方法设法做了类似的事情......
我使用了.BindWith<>()
绑定方法......
this.Kernel.Bind(b => b.FromAssembliesMatching("*")
.SelectAllClasses()
.InheritedFrom(typeof(Extensibility.IProducerPlugin))
.BindWith<PluginBindingGenerator<Extensibility.IProducerPlugin>>()
);
我已经实现了IBindingGenerator:
public class PluginBindingGenerator<T> : IBindingGenerator
{
public System.Collections.Generic.IEnumerable<Ninject.Syntax.IBindingWhenInNamedWithOrOnSyntax<object>> CreateBindings(Type type, Ninject.Syntax.IBindingRoot bindingRoot)
{
if (type != null && !type.IsAbstract && type.IsClass && typeof(T).IsAssignableFrom(type))
{
Ninject.Syntax.IBindingWhenInNamedWithOrOnSyntax<object> syntax = bindingRoot.Bind(typeof(Extensibility.IProducerPlugin)).ToProvider(new PluginProvider());
yield return (Ninject.Syntax.IBindingWhenInNamedWithOrOnSyntax<object>)syntax;
}
}
}
public class PluginProvider : IProvider<object>
{
private System.Collections.Generic.Dictionary<Domain.Identity.ClientIdentity, Extensibility.IProducerPlugin> plugins;
然后,提供者:
public PluginProvider()
{
this.plugins = new System.Collections.Generic.Dictionary<Domain.Identity.ClientIdentity, Extensibility.IProducerPlugin>();
}
public object Create(IContext ctx)
{
//... I don't know what to do here...
return objects;
}
public Type Type
{
get { throw new NotImplementedException(); }
}
}