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?
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.
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.
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>();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With