Lazy<> Ninject Injection
Asked Answered
F

3

8

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.

Freestone answered 10/6, 2013 at 9:31 Comment(0)
F
9
Bind(typeof (Lazy<IPsoriasisReportUserControl>)).ToMethod(
            ctx => new Lazy<IPsoriasisReportUserControl>(() =>
                  Kernel.Get<IPsoriasisReportUserControl>()));
Freestone answered 10/6, 2013 at 10:40 Comment(1)
This answer works. But you can also do the other answer by simply using the NInject Extension factory. It will work automatically.Ascanius
K
13

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

Khat answered 12/6, 2013 at 15:52 Comment(1)
Actually, a link to the wiki might be the more useful reference than the source code repository, as it shows how the injection of Lazy<T> is supposed to happen: github.com/ninject/Ninject.Extensions.Factory/wiki/LazyCesium
F
9
Bind(typeof (Lazy<IPsoriasisReportUserControl>)).ToMethod(
            ctx => new Lazy<IPsoriasisReportUserControl>(() =>
                  Kernel.Get<IPsoriasisReportUserControl>()));
Freestone answered 10/6, 2013 at 10:40 Comment(1)
This answer works. But you can also do the other answer by simply using the NInject Extension factory. It will work automatically.Ascanius
M
1

You need a default public constructor on Lazy :

public Lazy() {}
Miscellanea answered 10/6, 2013 at 9:37 Comment(4)
there is an parameterless constructor. The injection does not use that I think. Do not know how can I configure that<Freestone
Lazy probably refers to the type in the BCL. You'll be hard pressed to change it.Senter
[TestMethod] public void UC_DiagnosticReport_How_Lazy_Works() { Lazy<IPsoriasisReportUserControl> a = new Lazy<IPsoriasisReportUserControl>( NinjectService.Get<IPsoriasisReportUserControl>); var b = a.Value; Assert.IsNotNull(b); } this works. I need thisFreestone
You have to bind IPsoriasisReportUserControl like this : kernel.Bind(typeof(IPsoriasisReportUserControl)).To(typeof(PsoriasisReportUserControl); BEFORE the bind of Lazy<>Miscellanea

© 2022 - 2024 — McMap. All rights reserved.