Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resolve a dependency inside a Ninject Module?

I am using Ninject 2 with Asp.Net MVC 3. I have following module.

public class ServiceModule : NinjectModule
{
    public override void Load()
    {
        //I need to get the 'configHelper' from Ninject Container. 
        IConfigHelper configHelper = ResolveConfigHelperHere();

        Bind<IMyService>().To<MyServiceImpl>().WithConstructorArgument("myArg", configHelper.MyProperty);

    }
}

How do we get the instance of 'IConfigHelper' which is already Bind in Ninject module?

like image 262
Amitabh Avatar asked Mar 23 '11 17:03

Amitabh


People also ask

What is ninject dependency injection?

Ninject is a lightweight dependency injection framework for . NET applications. It helps you split your application into a collection of loosely-coupled, highly-cohesive pieces, and then glue them back together in a flexible manner.

What is a ninject module?

The Ninject modules are the tools used to register the various types with the IoC container. The advantage is that these modules are then kept in their own classes. This allows you to put different tiers/services in their own modules.


1 Answers

var helper = Kernel.Get<IConfigHelper>();
Bind<IMyService>().To<MyServiceImpl>().WithConstructorArgument(
    "myArg",
    helper.MyProperty
);

and here's a full example:

public interface IConfigHelper
{
    string MyProperty { get; set; }
}

public class ConfigHelper : IConfigHelper
{
    public string MyProperty { get; set; }
}

public interface IMyService
{

}

public class MyServiceImpl : IMyService
{
    public MyServiceImpl(string myArg)
    {

    }
}

public class HelperModule : NinjectModule
{
    public override void Load()
    {
        Bind<IConfigHelper>()
            .To<ConfigHelper>()
            .WithPropertyValue("MyProperty", "foo");
    }
}

public class ServiceModule : NinjectModule
{
    public override void Load()
    {
        var helper = Kernel.Get<IConfigHelper>();
        Bind<IMyService>()
            .To<MyServiceImpl>()
            .WithConstructorArgument("myArg", helper.MyProperty);
    }
}

class Program
{
    static void Main()
    {
        IKernel kernel = new StandardKernel(
            new HelperModule(),
            new ServiceModule()
        );

        var service = kernel.Get<IMyService>();
    }
}
like image 137
Darin Dimitrov Avatar answered Oct 04 '22 15:10

Darin Dimitrov