How to register an open generic that accepts parameters in LightInject?

250 views Asked by At

I have the following generic class, which depends on IBar:

public class Foo<T> : IFoo<T>
{
    public Foo(IBar bar, int value) { }
    
    ...
}

I would ideally register it using something like this in LightInject:

container.Register<IBar, Bar>();
container.Register<int, IFoo<>>((factory, value) => new Foo<>(factory.GetInstance<IBar>(), value))

so that at runtime, I am able to obtain an instance of IFoo with the supplied value:

container.GetInstance<IFoo<SomeType>>(42);

But this code obviously does not compile due to the use of the open generic IFoo<>:

container.Register<int, IFoo<>>((factory, value) => new Foo<>(...))

If only Foo was not a generic class, this would all work fine as per the official documentation: https://www.lightinject.net/#parameters.

Is there a solution for generic classes? Can this be written any other way and still achieve the same thing? I tried using the following syntax, but I'm loosing the ability to use a delegate that accepts a value (or at least I don't see how to do it)...

container.Register(typeof(IFoo<>), typeof(Foo<>));

Any idea?

0

There are 0 answers