Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to intercept a factory in lightinject

Not sure what to do here. invocationInfo.Proceed() always fails when trying to Intercept a factory that has constructor injection.

var container = new ServiceContainer();
container.Register<ICool,Cool>();
container.Register<ILogger, Logger>();
container.Register<IInterceptor, LoggingInterceptor>();

//Two problem lines
container.Register<int, IAwesome>((factory, value) => new Awesome(value, factory.GetInstance<ICool>()));
container.Intercept(sr => sr.ServiceType == typeof(IAwesome), sf => sf.GetInstance<IInterceptor>());

var awesome = container.GetInstance<int,IAwesome>(100);
awesome.Yo();

fails at this method in my interceptor.

public class LoggingInterceptor : IInterceptor
{
    private ILogger _logger;
    public LoggingInterceptor(ILogger logger)
    {
        _logger = logger;
    }
    public object Invoke(IInvocationInfo invocationInfo)
    {
        var returnValue = invocationInfo.Proceed(); //Exception here
        return returnValue;
    }
}

Exception:

An exception of type 'System.InvalidCastException' occurred in LightInject.dll but was not handled in user code

Additional information: Unable to cast object of type 'System.Func`1[ConsoleApplication1.IAwesome]' to type 'System.Object[]'.

Sorry I couldn't make a new tag for Lightinject. Not enough rep :/

like image 583
YurikoEX Avatar asked Feb 13 '23 00:02

YurikoEX


1 Answers

I am the author of LightInject and it has been confirmed to be a bug when intercepting service instances that relies on runtime arguments such as the Awesome class.

The bug has been fixed and I will post back here as soon as a new NuGet package is available.

Best regards

Bernhard Richter

like image 120
seesharper Avatar answered Feb 28 '23 04:02

seesharper