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

时间:2014-11-13 02:21:25

标签: ninject ninject-conventions

我想使用约定配置我的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));

更多
我有一个进程内服务总线。一些组件使用[Singleton]进行修饰,并将自己注册到服务总线:

// the constructor
public FooEventsListenerComponent(IServiceBus serviceBus) {
    serviceBus.Subscribe<FooEvent>(e => HandleFooEvent(e));
}

我需要在应用中创建一个位置来创建所有服务总线观察者的实例。在类型映射旁边做它很方便(但它是否合适?)因为1.类型已经枚举,2。我可以访问DI容器。

1 个答案:

答案 0 :(得分:0)

在您描述的情况下,我认为明确提供服务总线注册是有意义的。要将my answer扩展到您关于约定的其他问题:

为听众创建一个界面:

public interface IServiceBusSubscriber
{
    void SubscribeTo(IServiceBus serviceBus);
}

然后您可以调整您的约定以将从IServiceBusSubscriber继承的所有类型绑定到其默认接口(然后它们必须命名为FooServiceBusSubscriberBarServiceBusSubscriber)或{{1}明确地。

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

IServiceBusSubscriber