Question

I am using Ninject and I want to inject a property of my model.I have the following model

public class TCFormModel
{
    public string Name { get; set; }
    public IPNConBut pConBut { get; set; }
}

I want to inject IPNConBut with my ConBut class which implements IPNConBut.

public class ConBut : IPNConBut { ... }

How can I do this?

LATER EDIT - MORE INFO:

My model is used in a binder and it fails when it tries to create an instance of TCFormModel. It makes sense but how can avoid this? I tried with two constructors, one parameterless and one with the binding parameter. I also tried [Inject] on property and even on constructor and I had the same results. The constructor is never used.

public class TCFormModelBinder : IModelBinder
{
    private const string sessionKey = "TCFM_Model";

    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        TCFormModel model = null;
        if (controllerContext.HttpContext.Session != null)
        {
            model = (TCFormModel)controllerContext.HttpContext.Session[sessionKey];
        }

        if (model == null)
        {
            model = new TCFormModel();
            if (controllerContext.HttpContext.Session != null)
            {
                controllerContext.HttpContext.Session[sessionKey] = model;
            }
        }
        return model;
    }
}

Factory interface:

public interface IPNConButFactory
{
    IPNConBut Create();
}

No correct solution

OTHER TIPS

You can either us constructor injection:

public class TCFormModel
{
    public TCFormModle(IPNConBut pConBut) {
        this.pConBut = pConBut;
    }

    public string Name { get; set; }
    public IPNConBut pConBut { get; set; }
}

(which is usually recommend) or property injection:

public class TCFormModel
{
    public string Name { get; set; }

    [Inject]
    public IPNConBut pConBut { get; set; }
}

Also see: https://github.com/ninject/ninject/wiki/Injection-Patterns

And generally the wiki: https://github.com/ninject/ninject/wiki

Update:

I recommend using the https://github.com/ninject/ninject.extensions.factory extension.

Bind your factory interface as follows:

IBindingRoot.Bind<IPNConButFactory>().ToFactory();

Then, in TCFormModelBinder inject the IPNConButFactory and use it to create an instance. The Model should only need one constructor in case of constructor injection, or no (=default ctor) in case of property injection.

I'm not familiar with asp.net MVC so i'm not certain whether you can actuall inject something into TCFormModelBinder but i would guess so. At any rate, if you can't, you need to access the IKernel somehow and retrieve the factory from there.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top