使用ValueInjecter,有没有办法只注入一次给定的属性

Jas*_*yne 3 valueinjecter

鉴于3个班级,

A和B各有一个ID属性,然后是各种其他属性

和C,它有一个ID,以及A和B的组合属性,

我想要

C.InjectFrom(A);
C.InjectFrom(B);
Run Code Online (Sandbox Code Playgroud)

这样A中的ID就会被保留,而不会被B覆盖.

显然在这个简单的情况下,我可以颠倒两个调用的顺序,但在我的真实世界的例子中,它稍微复杂一点,我不能只通过排序来解决问题.

基本上我希望第二次注射忽略第一次注射已经处理过的任何事情,这可能会继续进行几次注射.这些注射中的一些也可以来自相同的物体

C.InjectFrom(A);
C.InjectFrom<SomeInjector>(A);
C.InjectFrom<SomeInjector2>(A);
C.InjectFrom<SomeInjector3>(A);
Run Code Online (Sandbox Code Playgroud)

等等

Omu*_*Omu 6

干得好:

using System;
using System.Collections.Generic;
using Omu.ValueInjecter;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {

            var a = new { Id = 1, P1 = "p1" };
            var b = new { Id = 2, P2 = "p2" };

            var c = new C();

            var propList = new List<string>();
            c.InjectFrom(new HandlePropOnce(propList), a);
            c.InjectFrom(new HandlePropOnce(propList), b);

            Console.WriteLine("Id = {0} P1 = {1} P2 = {2}", c.Id, c.P1, c.P2);
        }
    }

    public class C
    {
        public int Id { get; set; }

        public string P1 { get; set; }

        public string P2 { get; set; }
    }

    public class HandlePropOnce : ConventionInjection
    {
        private readonly IList<string> handledProps;

        public HandlePropOnce(IList<string> handledProps)
        {
            this.handledProps = handledProps;
        }

        protected override bool Match(ConventionInfo c)
        {
            if (handledProps.Contains(c.SourceProp.Name)) return false;

            var isMatch = c.SourceProp.Name == c.TargetProp.Name && c.SourceProp.Type == c.TargetProp.Type;

            if (isMatch) handledProps.Add(c.SourceProp.Name);
            return isMatch;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)