tzortzik
tzortzik

Reputation: 5133

How can I use same Ninject bindings in MVC and in my Models

I need to find a way to use Ninject in my classes (models) and also in my controllers of my MVC application.

How can I do to use the same bindings in both sides?

Right now I use my generated NinjectWebCommon.cs create my kernel and initialize the bootstrap:

    private static void RegisterServices(IKernel kernel)
    {
        System.Web.Mvc.DependencyResolver.SetResolver(
            new WebApplication1.Models.NinjectDependencyResolver(kernel)
            );

    } 

My NinjectDependencyResolver looks like:

public class NinjectDependencyResolver : IDependencyResolver
{
    private IKernel k;

    public NinjectDependencyResolver(IKernel kp)
    {
        this.k= kp;
        AddBindings();
    }

    public object GetService(Type serviceType)
    {
        return k.Get(serviceType);
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        return k.GetAll(serviceType);
    }

    private void AddBindings()
    {
        k.Bind<ISerializer>().To<MySerializer>();
    }
}

MySerializer is my serialization class.

For my controllers, this part works fine.

But let's say I have the following model:

public class MyButton
{

    ISerializer serializer;

    public MyButton(ISerializer weapon) 
    {
        serializer = weapon;
    }

    public string ToSString()
    {
        return serializer.serialize("my string - ");
    }
}

How can I make Ninject work also for my model?

Thank you!

Upvotes: 0

Views: 105

Answers (1)

Abhilash
Abhilash

Reputation: 367

You may inject the model as well and add the following binding

    private void AddBindings()
    {
        k.Bind<IMySerializer>().To<MySerializer>();
        k.Bind<IModel>().To<Model>();
    }

or if you are not injecting your model then you could do something like this thread says

using ninject to inject dependency to The Model classes or non-controller classes

Upvotes: 1

Related Questions