Ninject 2个依赖类的上下文绑定,具有相同构造函数参数

时间:2016-02-27 22:58:25

标签: c# dependency-injection ninject contextual-binding

在两个类具有相同底层接口依赖关系的场景中,无法确定如何管理上下文绑定,但每个类ctor的参数命名方式不同。下面的伪代码演示了我的情况:

    interface IThing { }
    public class Thing1 : IThing { public Thing1(string fileCode) { } }
    public class Thing2 : IThing { public Thing2(string fileCode) { } }
    interface IThingFactory { IThing CreateThing(string fileCode); }

    interface IDependentThing { }
    public class A : IDependentThing { public A(string fileCode, IThingFactory thingFactory) { } }
    public class B : IDependentThing { public B(string fileCd, IThingFactory thingFactory) { } } //How to handle binding for this dependent?
    interface IDependentThingFactory { IDependentThing CreateDependentThing(string fileCode); }

    //...

    public override void Load()
    {
        Bind<IThing>().ToMethod(ctx =>
        {
            var fileCode = ctx.Parameters.First(p => p.Name == "fileCode").GetValue(ctx, null) as string;
            IThing thing = null;

            if (fileCode == "FileType1")
            {
                Bind<Thing1>().ToSelf().WithConstructorArgument("fileCode", fileCode);
                thing = Kernel.Get<Thing1>();
            }
            else if (fileCode == "FileType2")
            {
                Bind<Thing2>().ToSelf().WithConstructorArgument("fileCode", fileCode);
                thing = Kernel.Get<Thing2>();
            }
            return thing;
        });

        Bind<IThingFactory>().ToFactory();
        Bind<IDependentThingFactory>().ToFactory();
    }

//Later...
using (TextReader tr = new StreamReader(path))
{
    string firstLine = tr.ReadLine();

    if (firstLine.Substring(838, 1) == ".")
    {
        fileCode = "FileType1";
    }
    else if (firstLine.Substring(883, 1) == ".")
    {
        fileCode = "FileType2";
    }

    //won't work for creating B
    Kernel.Get<IDependentThing>(new ConstructorArgument("fileCode", fileCode));

    //or maybe...

    //seems to eliminate my problem by allowing me to handle variations
    //in parameter names  from within A and B's ctors, but looks like it
    //requires injecting factories along the chain (see A & B ctor arguments).
    dependentThingFactory.CreateDependentThing(fileCode) 
};

fileCode的计算基于对本地文件的一些分析。一旦确定了文件类型,我希望Ninject交回适当的对象来处理该文件

我如何处理B的绑定,因为我定义的现有绑定需要一个具有不同名称的构造函数参数?有没有更好的方法来做到这一点?

我想我可以使用p.Name == "fileCode" || p.Name == "fileCd",但我无法摆脱我做错事(感觉凌乱)的感觉。另外,我对于按名称提取参数并不感到兴奋,而且我想过可能会创建一个自定义类型,它可以让Ninject更具体地匹配字符串参数。从我站立的地方来看,我或者只是管理多个参数名称的情况,或者切换到自定义类型作为我的参数而不是字符串。

1 个答案:

答案 0 :(得分:1)

使参数注入更安全,并使其可用于整个分辨率上下文

而不是&#34;命名参数&#34;你可以使用&#34;类型匹配&#34;或&#34;键入&#34;参数。工厂IInstanceProvider可以换成另一个工厂:

kernel.Bind<IThingFactory>()
      .ToFactory(() => new TypeMatchingArgumentInheritanceInstanceProvider());

注意:

  • 这个IInstanceProvider也会使论证进一步提供&#34;下游&#34; (它&#34;继承&#34;参数)
  • string非常详细,因此您可能希望选择将其换成其他类型,例如class ConnectionInfo

上下文绑定与参数注入相结合

因此,我们假设我们创建自己的FileType类型比使用string更加冗长:

public class FileCode
{
    public FileCode(string value)
    {
        Value = value;
    }

    public string Value { get; private set; }
}

(也许你想用enum替换它?)

由于您的要求更加复杂,我们必须稍微改变一下。 我们将创建自己的IConstructorArgument,以便轻松地将其与When - 上下文绑定进行匹配,并根据类型匹配(如上所述)注入其值:

internal class FileCodeParameter : IConstructorArgument
{
    private readonly FileCode fileCode;

    public FileCodeParameter(FileCode fileCode)
    {
        this.fileCode = fileCode;
    }

    public string Name { get { return "File Code Parameter"; } }

    public bool ShouldInherit { get { return true; } }

    public FileCode FileCode  { get { return this.fileCode; } }

    public bool Equals(IParameter other)
    {
        var otherFileCodeParameter = other as FileCodeParameter;
        if (otherFileCodeParameter == null)
        {
            return false;
        }

        return otherFileCodeParameter.fileCode == this.fileCode;
    }

    public object GetValue(IContext context, ITarget target)
    {
        return this.fileCode;
    }

    public bool AppliesToTarget(IContext context, ITarget target)
    {
        return target.Type == typeof(FileCode);
    }
}

现在让我创建一些示例代码,以便稍后验证它是否有效:

public interface IThing
{
    FileCode FileCode { get; }
}

public abstract class Thing : IThing
{
    protected Thing(FileCode fileCode)
    {
        FileCode = fileCode;
    }

    public FileCode FileCode { get; private set; }
}

public class ThingFoo : Thing
{
    public ThingFoo(FileCode fileCode) : base(fileCode) { }
}

public class ThingBar : Thing
{
    public ThingBar(FileCode fileCode) : base(fileCode) { }
}

public interface IOtherThing
{
    FileCode FileCode { get; }
}

public abstract class OtherThing : IOtherThing
{
    protected OtherThing(FileCode fileCode)
    {
        FileCode = fileCode;
    }

    public FileCode FileCode { get; private set; }
}

public class OtherThingFoo : OtherThing
{
    public OtherThingFoo(FileCode fileCode) : base(fileCode) { }
}

public class OtherThingBar : OtherThing
{
    public OtherThingBar(FileCode fileCode) : base(fileCode) { }
}

public class OtherThingWrapper
{
    public OtherThingWrapper(IOtherThing otherThing)
    {
        OtherThing = otherThing;
    }

    public IOtherThing OtherThing { get; private set; }
}

public class FileProcessor
{
    public FileProcessor(IThing thing, OtherThingWrapper otherThingWrapper)
    {
        Thing = thing;
        OtherThingWrapper = otherThingWrapper;
    }

    public IThing Thing { get; private set; }
    public OtherThingWrapper OtherThingWrapper { get; private set; }
}

缺少什么?工厂。我们可以使用ToFactory绑定自定义IInstanceProvider,但除非我们要创建大量工厂FileCodeParameter,否则不要认为它有意义,所以让# 39;保持简单:

public interface IFileProcessorFactory
{
    FileProcessor Create(FileCode fileCode);
}

internal class FileProcessorFactory : IFileProcessorFactory
{
    private readonly IResolutionRoot resolutionRoot;

    public FileProcessorFactory(IResolutionRoot resolutionRoot)
    {
        this.resolutionRoot = resolutionRoot;
    }

    public FileProcessor Create(FileCode fileCode)
    {
        return this.resolutionRoot.Get<FileProcessor>(new FileCodeParameter(fileCode));
    }
}

现在让我们一起来吧:

public class Test
{
    [Fact]
    public void FactMethodName()
    {
        var fooFileCode = new FileCode("foo");
        var barFileCode = new FileCode("bar");

        var kernel = new StandardKernel();
        kernel
            .Bind<IFileProcessorFactory>()
            .To<FileProcessorFactory>();

        kernel
            .Bind<IThing>()
            .To<ThingFoo>()
            .WhenFileCode(fooFileCode);
        kernel
            .Bind<IThing>()
            .To<ThingBar>()
            .WhenFileCode(barFileCode);

        kernel
            .Bind<IOtherThing>()
            .To<OtherThingFoo>()
            .WhenFileCode(fooFileCode);
        kernel
            .Bind<IOtherThing>()
            .To<OtherThingBar>()
            .WhenFileCode(barFileCode);


        var fileProcessor = kernel.Get<IFileProcessorFactory>().Create(barFileCode);
        fileProcessor.Thing.Should().BeOfType<ThingBar>();
        fileProcessor.Thing.FileCode.Should().Be(barFileCode);
        fileProcessor.OtherThingWrapper.OtherThing.Should().BeOfType<OtherThingBar>();
        fileProcessor.OtherThingWrapper.OtherThing.FileCode.Should().Be(barFileCode);
    }
}

public static class BindingExtensionsForFileCodes
{
    public static IBindingInNamedWithOrOnSyntax<T> WhenFileCode<T>(
        this IBindingWhenSyntax<T> syntax,
        FileCode fileCode)
    {
        return syntax.When(req => req
            .Parameters
            .OfType<FileCodeParameter>()
            .Single()
            .FileCode.Value == fileCode.Value);
    }
}

那就是它!   - FileCode都被注入并用于选择实现   - 由于参数是&#34;继承&#34;,它也可以在对象树下更深入地工作。

下面,仅供参考,所有代码更容易复制&amp;粘贴:

using FluentAssertions;
using Ninject;
using Ninject.Activation;
using Ninject.Parameters;
using Ninject.Planning.Targets;
using Ninject.Syntax;
using System.Linq;
using Xunit;

namespace NinjectTest.ParameterContextual
{
    public class FileCode
    {
        public FileCode(string value)
        {
            Value = value;
        }

        public string Value { get; private set; }
    }

    public interface IThing
    {
        FileCode FileCode { get; }
    }

    public abstract class Thing : IThing
    {
        protected Thing(FileCode fileCode)
        {
            FileCode = fileCode;
        }

        public FileCode FileCode { get; private set; }
    }

    public class ThingFoo : Thing
    {
        public ThingFoo(FileCode fileCode) : base(fileCode) { }
    }

    public class ThingBar : Thing
    {
        public ThingBar(FileCode fileCode) : base(fileCode) { }
    }

    public interface IOtherThing
    {
        FileCode FileCode { get; }
    }

    public abstract class OtherThing : IOtherThing
    {
        protected OtherThing(FileCode fileCode)
        {
            FileCode = fileCode;
        }

        public FileCode FileCode { get; private set; }
    }

    public class OtherThingFoo : OtherThing
    {
        public OtherThingFoo(FileCode fileCode) : base(fileCode) { }
    }

    public class OtherThingBar : OtherThing
    {
        public OtherThingBar(FileCode fileCode) : base(fileCode) { }
    }

    public class OtherThingWrapper
    {
        public OtherThingWrapper(IOtherThing otherThing)
        {
            OtherThing = otherThing;
        }

        public IOtherThing OtherThing { get; private set; }
    }

    public class FileProcessor
    {
        public FileProcessor(IThing thing, OtherThingWrapper otherThingWrapper)
        {
            Thing = thing;
            OtherThingWrapper = otherThingWrapper;
        }

        public IThing Thing { get; private set; }
        public OtherThingWrapper OtherThingWrapper { get; private set; }
    }

    public interface IFileProcessorFactory
    {
        FileProcessor Create(FileCode fileCode);
    }

    internal class FileProcessorFactory : IFileProcessorFactory
    {
        private readonly IResolutionRoot resolutionRoot;

        public FileProcessorFactory(IResolutionRoot resolutionRoot)
        {
            this.resolutionRoot = resolutionRoot;
        }

        public FileProcessor Create(FileCode fileCode)
        {
            return this.resolutionRoot.Get<FileProcessor>(new FileCodeParameter(fileCode));
        }
    }

    public class Test
    {
        [Fact]
        public void FactMethodName()
        {
            var fooFileCode = new FileCode("foo");
            var barFileCode = new FileCode("bar");

            var kernel = new StandardKernel();
            kernel
                .Bind<IFileProcessorFactory>()
                .To<FileProcessorFactory>();

            kernel
                .Bind<IThing>()
                .To<ThingFoo>()
                .WhenFileCode(fooFileCode);
            kernel
                .Bind<IThing>()
                .To<ThingBar>()
                .WhenFileCode(barFileCode);

            kernel
                .Bind<IOtherThing>()
                .To<OtherThingFoo>()
                .WhenFileCode(fooFileCode);
            kernel
                .Bind<IOtherThing>()
                .To<OtherThingBar>()
                .WhenFileCode(barFileCode);


            var fileProcessor = kernel.Get<IFileProcessorFactory>().Create(barFileCode);
            fileProcessor.Thing.Should().BeOfType<ThingBar>();
            fileProcessor.Thing.FileCode.Should().Be(barFileCode);
            fileProcessor.OtherThingWrapper.OtherThing.Should().BeOfType<OtherThingBar>();
            fileProcessor.OtherThingWrapper.OtherThing.FileCode.Should().Be(barFileCode);
        }
    }

    internal class FileCodeParameter : IConstructorArgument
    {
        private readonly FileCode fileCode;

        public FileCodeParameter(FileCode fileCode)
        {
            this.fileCode = fileCode;
        }

        public string Name { get { return "File Code Parameter"; } }

        public bool ShouldInherit { get { return true; } }

        public FileCode FileCode  { get { return this.fileCode; } }

        public bool Equals(IParameter other)
        {
            var otherFileCodeParameter = other as FileCodeParameter;
            if (otherFileCodeParameter == null)
            {
                return false;
            }

            return otherFileCodeParameter.fileCode == this.fileCode;
        }

        public object GetValue(IContext context, ITarget target)
        {
            return this.fileCode;
        }

        public bool AppliesToTarget(IContext context, ITarget target)
        {
            return target.Type == typeof(FileCode);
        }
    }

    public static class BindingExtensionsForFileCodes
    {
        public static IBindingInNamedWithOrOnSyntax<T> WhenFileCode<T>(
            this IBindingWhenSyntax<T> syntax,
            FileCode fileCode)
        {
            return syntax.When(req => req
                .Parameters
                .OfType<FileCodeParameter>()
                .Single()
                .FileCode.Value == fileCode.Value);
        }
    }
}