Проблема с множественным внедрением зависимости с помощью Ninject - PullRequest
1 голос
/ 05 декабря 2010

В качестве отказа от ответственности я скажу, что я все еще пытаюсь обернуть голову вокруг всего шаблона DI, поэтому я думаю, что нет необходимости говорить, что мой код, вероятно, может иметь серьезную концептуальную ошибку.

При этомя пытаюсь внедрить два свойства в следующую реализацию:

interface ISurface
{
    string Use();
}

class Canvas : ISurface
{
    public string Use()
    {
        return "canvas";
    }
}

class Hardboard : ISurface
{
    public string Use()
    {
        return "hardboard";
    }
}

interface IMaterial
{
    string Apply(string surface);
}

class Oil : IMaterial
{
    public string Apply(string surface)
    {
        return "painted with oil on {0}";
    }
}

class Acrylic : IMaterial
{
    public string Apply(string surface)
    {
        return "painted with acrylic on {0}";
    }
}

class Artist
{
    public string Name { get; set; }

    [Inject]
    public IMaterial Material { get; set; }

    [Inject]
    public ISurface Surface { get; set; }

    public string Paint()
    {
        return Material.Apply(Surface.Use());
    }
}

class PainterModule : NinjectModule
{
    public override void Load()
    {
        Bind<ISurface>().To<Canvas>();
        Bind<IMaterial>().To<Oil>();
        Bind<Artist>().ToSelf();
    }
}

Поэтому, когда я вызываю метод:

class Program
{
    static void Main(string[] args)
    {
        try
        {
            IKernel kernel = new StandardKernel(new PainterModule());
            Artist artist = kernel.Get<Artist>();
            artist.Name = "Peter Gibbons";
            Console.WriteLine(artist.Name + artist.Paint());
        }
        catch (Exception error)
        {
            Console.WriteLine(error.Message);
            throw;
        }
        finally
        {
            Console.ReadKey(true);
        }
    }
}

Удивительно, но для меня это выдает:

"Peter Gibbons painted with oil on {0}"

1 Ответ

1 голос
/ 06 декабря 2010

Похоже, что все разрешается нормально, но вы хотите, чтобы Oil.Apply() использовал string.Format()?

class Oil : IMaterial
{
    public string Apply(string surface)
    {
        return string.Format("painted with oil on {0}", surface);
    }
}

Это должно вернуть "Питер Гиббонс, нарисованный маслом на холсте".

...