Skip to content

Injecting runtime configuration #46

Description

@PatrikBak

My problem:

public class RuntimeConfiguration
{
    public int Number { get; set; }
}

public class DependencyOfDependency
{
    public DependencyOfDependency(RuntimeConfiguration test)
    {
        Console.WriteLine(test.Number);
    }
}

public class Dependency
{
    public Dependency(DependencyOfDependency d) { }
}

public interface IDependencyFactory
{
    Dependency Create(RuntimeConfiguration configuration);
}

var kernel = new StandardKernel(new FuncModule());
kernel.Bind<Dependency>().ToSelf();
kernel.Bind<DependencyOfDependency>().ToSelf();
kernel.Bind<IDependencyFactory>().ToFactory();
kernel.Get<IDependencyFactory>().Create(new RuntimeConfiguration { Number = 42 });

It prints 0 instead of 42.

My solution:

public class DependencyFactory : IDependencyFactory
{
    private readonly IKernel kernel;

    public DependencyFactory(IKernel kernel)
    {
        this.kernel = kernel;
    }

    public Dependency Create(RuntimeConfiguration configuration)
    {
        lock (kernel)
        {
            kernel.Bind<RuntimeConfiguration>().ToConstant(configuration);

            var result = kernel.Get<Dependency>();

            kernel.Unbind<RuntimeConfiguration>();

            return result;
        }
    }
}

kernel.Bind<IDependencyFactory>().To<DependencyFactory>();

Problems with this approach:

(1) It feels like an unnecessary hack.
(2) Possible performance issues due to locking.

I can't figure out a better solution though. Any advice?

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions