Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lazy<> Ninject Injection

I use ninject framework. In my code I have a Lazy object. I can create an instance, but when I call the value property I got an exception.

 private Lazy<IPsoriasisReportUserControl> psoriasisReportUserControl;

[Inject]
    public Lazy<IPsoriasisReportUserControl> PsoriasisReportUserControl
    {
        get { return psoriasisReportUserControl; }
        set { psoriasisReportUserControl = value; }
    }

I got

The lazily-initialized type does not have a public, parameterless constructor

exception because the injection does not inject the method into the constructor. I think I have to write a method to the bind what Creates a new instance.

like image 477
Lajos Avatar asked Jun 10 '13 09:06

Lajos


3 Answers

Use the factory extension for Ninject https://github.com/ninject/ninject.extensions.factory

like image 169
Remo Gloor Avatar answered Nov 14 '22 22:11

Remo Gloor


Bind(typeof (Lazy<IPsoriasisReportUserControl>)).ToMethod(
            ctx => new Lazy<IPsoriasisReportUserControl>(() =>
                  Kernel.Get<IPsoriasisReportUserControl>()));
like image 39
Lajos Avatar answered Nov 14 '22 22:11

Lajos


You need a default public constructor on Lazy :

public Lazy() {}
like image 1
Joffrey Kern Avatar answered Nov 14 '22 21:11

Joffrey Kern