Search code examples
c#dependency-injectionninjectsimple-injector

Equivalent Ninject code with Simple Injector


Decided to switch from Ninject to Simple Injector and one problem i'm having here is trying to convert this code into Simple Injectors Equivalent:

var resolver = new SomeResolver(container); 

container.Rebind(typeof(IHubConnectionContext<dynamic>))
    .ToMethod(context =>
        resolver.Resolve<IConnectionManager>().GetHubContext<PlanHub>().Clients
    ).WhenInjectedInto<PlanHubService>();

Solution

    • The use of Rebind in Ninject is equivalent to using Register with AllowOverridingRegistrations set to true in Simple Injector.
    • WhenInjectedInto in Ninject is equivalent to the use of RegisterConditional in Simple Injector.
    • The ToMethod in Ninject typically equals to using Register<T>(Func<T>) in Simple Injector, but in conjunction with RegisterConditional you will have to fall back to creating a Registration using Lifestyle.CreateRegistration<T>(Func<T>, Container).

    You can therefore rewrite your binding to the following Simple Injector code:

    container.RegisterConditional(
        typeof(IHubConnectionContext<dynamic>),
        Lifestyle.Transient.CreateRegistration(
            () => container.GetInstance<IConnectionManager>().GetHubContext<PlanHub>().Clients,
            container),
        WhenInjectedInto<PlanHubService>);
    

    Where WhenInjectedInto<T> is a custom helper method defined as follows:

    private static bool WhenInjectedInto<T>(PredicateContext context) =>
        typeof(T).IsAssignableFrom(context.Consumer.ImplementationType);