Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Injecting runtime configuration #46

Open
PatrikBak opened this issue Feb 8, 2019 · 0 comments
Open

Injecting runtime configuration #46

PatrikBak opened this issue Feb 8, 2019 · 0 comments

Comments

@PatrikBak
Copy link

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant