Search code examples
dependency-injectionnancy

Nancy register dependency with type argument


Nancy auto-registration of dependencies is having trouble resolving a dependency with a type argument, so I'm trying to manually register it and cannot figure it out.

public abstract class BaseE { }
public abstract class BaseS<T> where T : BaseE { }
public class E : BaseE { }
public interface ISomething { }
public class S<T> : BaseS<T> where T : BaseE, ISomething { }

I want ISomething to be auto-resolved to class S, but that's not working, so I created a custom bootstrapper:

public class CustomBootstrapper : DefaultNancyBootstrapper
{
        protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
        {
            base.ConfigureApplicationContainer(container);
            // Works fine, but not sure if necessary
            container.Register<E, BaseE>();
            // Cannot get the syntax right, doesn't compile
            // ??? container.Register<ISomething, S<E>>();
        }
}

I can't seem to figure out the syntax. The line container.Register<ISomething, S<E>>(); gives me a compile error: The type S<E> cannot be used as type parameter 'RegisterImplementation' in the generic type or method 'TinyIoCContainer.Register<RegisterType, RegisterImplementation()'. There is no implicit reference conversion from 'S<E>' to 'ISomething'

Please help me figure out what the correct syntax / correct way to register a dependency with a type argument.


Solution

  • The error was due to incorrect syntax as pointed out by qujck.

    public class S<T> : BaseS<T> where T : BaseE, ISomething { }
    

    should be

    public class S<T> : BaseS<T>, ISomething where T : BaseE { }
    

    The first syntax says that type T extends BaseE AND implements ISomething, the second syntax says that type T only extends BaseE (and S implements ISomething). Dependency auto-injection is now working as expected.