Ninject,将构造函数参数传递给内核

时间:2012-02-16 11:55:29

标签: c#-4.0 dependency-injection ninject-2

这是我的问题: 每次我从内核请求一个实例时,我想将其中一个值传递给构造函数。我在下面写了一些代码来说明问题。测试没有失败,所以我猜这有效,但看起来确实很难看。使用Ninject有更好,更清洁的方法吗?或者我应该重新考虑我的设计?所有建议都表示赞赏。

[TestFixture]
public class Sandbox
{
    [Test]
    public void Run_Forrest_Run()
    {
        using (var kernel = new StandardKernel(new Module()))
        {
            var connection = new Connection(Guid.NewGuid().ToString());
            var downloader = kernel.Get<IDownloader>(new IParameter[] { new Parameter("connection", connection, false) });

            Assert.That(downloader.Connection.Info, Is.EqualTo(connection.Info));
        }
    }

    public class Downloader : IDownloader
    {
        public Downloader(Connection connection, ILogger logger)
        {
            Connection = connection;
            Logger = logger;
        }

        public Connection Connection { get; private set; }

        public void Download()
        {
            Logger.Log("Downloading...");
        }

        public ILogger Logger { get; private set; }
    }

    public interface IDownloader
    {
        Connection Connection { get; }
        void Download();
    }

    public class ConsoleLogger : ILogger
    {
        public void Log(string message)
        {
            Console.Out.WriteLine(message);
        }
    }

    public interface ILogger
    {
        void Log(string message);
    }

    public class Connection
    {
        public Connection(string info)
        {
            Info = info;
        }

        public string Info { get; private set; }
    }

    public class Module : NinjectModule
    {
        public override void Load()
        {
            Bind<ILogger>().To<ConsoleLogger>();

            Bind<IDownloader>().To<Downloader>()
                .WithConstructorArgument("connection", context =>
                {
                    var p = context.Parameters.First(x => x.Name == "connection");
                    return p.GetValue(context, null);
                });
            }
    }
}

1 个答案:

答案 0 :(得分:15)

如果你总是想在解析Connection时指定IDownloader,那么我认为ConstructorArgumentIParameter)就是你要找的:< / p>

[Test]
public void Run_Forrest_Run()
{
    using (var kernel = new StandardKernel(new Module()))
    {
        var connection = new Connection(Guid.NewGuid().ToString());
        var downloader = kernel.Get<IDownloader>(new [] { 
            new ConstructorArgument("connection", connection) });

        Assert.That(downloader.Connection.Info, Is.EqualTo(connection.Info));
    }
}

public class Module : NinjectModule
{
    public override void Load()
    {
        Bind<ILogger>().To<ConsoleLogger>();
        Bind<IDownloader>().To<Downloader>();
    }
}