Ninject:在配置期间实例化服务

Ninject:在配置期间实例化服务,ninject,ninject-conventions,Ninject,Ninject Conventions,我想使用约定配置ninject容器,并同时创建所有选定服务的实例。我目前的解决办法是: var singletons = new List<Type>(); kernel.Bind(x => x.FromThisAssembly() // Scans currently assembly .SelectAllClasses() .WithAttribute&l

我想使用约定配置ninject容器,并同时创建所有选定服务的实例。我目前的解决办法是:

        var singletons = new List<Type>();
        kernel.Bind(x =>
            x.FromThisAssembly() // Scans currently assembly
                .SelectAllClasses()
                .WithAttribute<SingletonAttribute>()
                .Where(type =>
                {
                    var include = MySpecialFilterOfSomeSort(type);
                    if (include)
                    {
                        singletons.Add(type);
                    }
                    return include;
                }) // Skip any non-conventional bindings
                .BindDefaultInterfaces() // Binds the default interface to them
                .Configure(c => c.InSingletonScope()) // Object lifetime is current request only
            );
            singletons.ForEach(s => kernel.Get(s));
var singleton=newlist();
Bind(x=>
x、 FromThisAssembly()//扫描当前程序集
.SelectAllClasses()
.WithAttribute()
。其中(类型=>
{
var include=MySpecialFilterOfSomeSort(类型);
如果(包括)
{
添加(类型);
}
回报包括;
})//跳过任何非常规绑定
.BindDefaultInterfaces()//将默认接口绑定到它们
.Configure(c=>c.InSingletonScope())//对象生存期仅为当前请求
);
singletons.ForEach(s=>kernel.Get(s));
更多
我有一个进程内服务总线。一些组件用[Singleton]装饰,并将自己注册到服务总线:

// the constructor
public FooEventsListenerComponent(IServiceBus serviceBus) {
    serviceBus.Subscribe<FooEvent>(e => HandleFooEvent(e));
}
//构造函数
公共食品事件侦听组件(IServiceBus服务总线){
订阅(e=>HandleFooEvent(e));
}

我需要在应用程序中创建所有服务总线观察员的实例。在类型映射旁边执行它很方便(但是否合适?),因为1。类型已枚举,2。我可以访问DI容器。

在您描述的情况下,我认为明确服务总线注册是有意义的。要进一步讨论有关约定的其他问题,请执行以下操作:

为侦听器创建一个接口:

public interface IServiceBusSubscriber
{
    void SubscribeTo(IServiceBus serviceBus);
}
然后,您可以调整您的约定,将继承自
IServiceBusSubscriber
的所有类型绑定到它们的默认接口(然后它们必须命名为
FooServiceBusSubscriber
BarServiceBusSubscriber
)或显式绑定到
IServiceBusSubscriber

使用所有绑定初始化内核后,只需执行以下操作:

IServiceBus serviceBus = kernel.Get<IServiceBus>();
foreach(IServiceBusSubscriber subscriber in kernel.GetAll<IServiceBusSubscriber>())
{
    subscriber.SubscribeTo(serviceBus)
}
IServiceBus serviceBus=kernel.Get();
foreach(kernel.GetAll()中的IServiceBussSubscriber订户)
{
subscriber.SubscribeTo(服务总线)
}

为什么需要实例化它们?它们不应该被实例化为应用程序的一部分吗?如果没有,它们是否共享任何公共逻辑,例如,您是否需要在应用程序关闭时告诉它们“关闭”?或在实例化后“初始化”@BatteryBackupUnit,公平的问题。我已经更新了这个问题。有没有办法为没有接口但用属性修饰的服务执行kernel.GetAll?类似于:
kernel.GetAllWithAttribute()
不,您不能这样做。您只能将属性用于绑定(约定),而不能用于检索/实例化。