Search code examples
c#observableninject.net-4.8

How Can I Resolve Other Dependencies within Ninject .OnActivation?


I am using Ninject to set up bindings for a class which is an IObservable.

I have set up a rebind to ensure that the IObservable has it's IObserver subscribed as follows...

kernel.Rebind<IAddressRepository>().To<AddressRepository>().InRequestScope()
                .OnActivation(repo => repo
                    .Subscribe(new SyncTrackerDataEventObserver<Address, AddressRepository>()));

This seems to work OK but it really isn't ideal. SyncTrackerDataEventObserver will, when it's more than a stub have dependencies of it's own. Then we end up with this...

kernel.Rebind<IAddressRepository>().To<AddressRepository>().InRequestScope()
                .OnActivation(repo => repo
                    .Subscribe(new SyncTrackerDataEventObserver<Address, AddressRepository>(new SyncTrackerRepository(new SyncDataSource))));

Ouch!!

What I want to do is make use of the existing bindings at this point. I'd expect to be able to write something like this (but this is just made up..)

kernel.Rebind<IAddressRepository>().To<AddressRepository>().InRequestScope()
                .OnActivation(repo => repo
                    .Subscribe(kernel.Resolve<ISyncTrackerDataEventObserver>()));

What is the correct way to achieve this without creating a hell of hard coded dependencies and breaking IoC paradigms?


Solution

  • This was quite straightforward when I figured out where to look. kernel.TryGet<> will get you the service type from the current bindings.

    kernel.Rebind<IAddressRepository>().To<AddressRepository>().InBackgroundJobScope()
        .OnActivation(repo => repo
            .Subscribe(kernel.TryGet<SyncTrackerDataEventObserver<Address, AddressRepository>>() 
                ?? throw new ObserverBindingException("Address")));
    

    (where ObserverBindingException is a custom exception type I created just for this purpose).