Search code examples
c#genericstinyioc

TinyIoCContainer registration with generics


I am using .NET Nancy's TinyIoCContainer for dependency injection. I am trying to register an interface and its implementation through generics, like so:

Register(container, typeof(IUserService), typeof(UserService));

private void Register<TInterface, TImplementation>(TinyIoCContainer container)
                        where TInterface : class
                        where TImplementation : class, TInterface
{
    container.Register<TInterface, TImplementation>();
}

This gives me the following exception:

Cannot register type System.Type - abstract classes or interfaces are not valid implementation types for SingletonFactory.

Which suggests SingletonFactory cannot work with generics. I have also tried registering the type as multi-instance:

container.Register<TInterface, TImplementation>().AsMultiInstance();

And I get the same exception.

The closest question I've been able to find is about a slightly different issue, generic interfaces: https://github.com/NancyFx/Nancy/issues/2747 and https://github.com/grumpydev/TinyIoC/issues/8

Has anyone been able to do it (through reflection, maybe?). Alternatively, is there an IoC container out there which supports it out of the box?


Solution

  • Update:

    Looks like this is a quirk of TinyIoCContainer. The code works fine with UnityContainer.