ThomasWeiss
ThomasWeiss

Reputation: 1302

Constructor parameter for injected class

Let's say I would like to inject an implementation of this interface:

interface IService { ... }

implemented as:

class MyService : IService
{
    public MyService(string s) { }
}

in an instance of this class:

class Target
{
    [Inject]
    public IService { private get; set; }
}

I do the injection by calling kernel.Inject(new Target()), but what if I would like to specify the parameter s of the constructor depending on some context when calling Inject? Is there a way to achieve such context-dependant service initialization at injection?

Thanks!

Upvotes: 1

Views: 501

Answers (2)

furier
furier

Reputation: 1977

  1. In most cases you should not use Field Injection, it should be used only in rare cases of circular dependencies.

  2. You should only use the kernel once at the start of your application and never again.

Example Code:

interface IService { ... }

class Service : IService
{
    public Service(string s) { ... }
}

interface ITarget { ... }

class Target : ITarget
{
    private IService _service;

    public Target(IServiceFactory serviceFactory, string s)
    {
        _service = serviceFactory.Create(s);
    }
}

interface ITargetFactory
{
    ITarget Create(string s);
}

interface IServiceFactory
{
    IService Create(string s);
}

class NinjectBindModule : NinjectModule 
{
    public NinjectBindModule()
    {
        Bind<ITarget>().To<Target>();
        Bind<IService>().To<Service>();
        Bind<ITargetFactory>().ToFactory().InSingletonScope();
        Bind<IServiceFactory>().ToFactory().InSingletonScope();
    }
}

Usage:

public class Program
{
    public static void Main(string[] args)
    {
        IKernel kernel = new StandardKernel(new NinjectBindModule());
        var targetFactory = kernel.Get<ITargetFactory>();
        var target = targetFactory.Create("myString");
        target.DoStuff();
    }
}

Upvotes: 2

ThomasWeiss
ThomasWeiss

Reputation: 1302

Simply done using parameters...

kernel.Inject(new Target(), new ConstructorArgument("s", "someString", true));

Upvotes: 0

Related Questions