Simple Dependency Injection with dynamic finder at runtime

Sometimes, we have multiple methods to be called, but it has to be determined at run time, so try to make it less coupled and use reflection to achieve this. The sample scenario here is for Field Type. We have different implementation for each different field type, such as text, date etc., and at run time, a DoSomething method should be called based on the field type.

Firstly, an interface is defined, which has methods called IsValid and DoSomething, IsValid method is used for a certain implementation which is valid for certain Fieldtype.

public enum TestFieldType
    {
        Text,
        Date
    }

    public interface ITestField
    {
        bool IsValid(TestFieldType fieldType);

        void DoSomething();

    }


    public class TextField: ITestField
    {
        public bool IsValid(TestFieldType fieldType)
        {
            return fieldType == TestFieldType.Text;
        }

        public void DoSomething()
        {
            // do something for Text Filed
        }
    }

    public class DateField : ITestField
    {
        public bool IsValid(TestFieldType fieldType)
        {
            return fieldType == TestFieldType.Date;
        }

        public void DoSomething()
        {
            // do something for Date Filed
        }
    }</pre>

Then, implement the finder method which accepts a TestFieldType parameter. And now we are able to GetTestField based on the parameter we pass, and call the respective DoSomething method as desired.

<pre class="lang:default decode:true ">public ITestField GetTestField(TestFieldType fieldType)
        {

            var type = typeof(ITestField);
            var types = Assembly.GetExecutingAssembly().GetTypes()
                .Where(p => type.IsAssignableFrom(p) && p.IsClass && !p.IsAbstract);

            foreach (var t in types)
            {
                var cField = (ITestField)Activator.CreateInstance(t);
                if (cField.IsValid(fieldType))
                {
                    return cField;
                }
            }
            return null;
        }


        [Test]
        public void TestMethod()
        {
            ITestField testField = GetTestField(TestFieldType.Text);
            testField.DoSomething();
        }