How to avoid Dependency Injection constructor madness?

前端 未结 9 1836
别跟我提以往
别跟我提以往 2020-11-22 03:59

I find that my constructors are starting to look like this:

public MyClass(Container con, SomeClass1 obj1, SomeClass2, obj2.... )

with ever

9条回答
  •  长发绾君心
    2020-11-22 04:47

    This is the approach I use

    public class Hero
    {
    
        [Inject]
        private IInventory Inventory { get; set; }
    
        [Inject]
        private IArmour Armour { get; set; }
    
        [Inject]
        protected IWeapon Weapon { get; set; }
    
        [Inject]
        private IAction Jump { get; set; }
    
        [Inject]
        private IInstanceProvider InstanceProvider { get; set; }
    
    
    }
    

    Here is a crude approach how to perform the injections and run constructor after injecting values. This is fully functional program.

    public class InjectAttribute : Attribute
    {
    
    }
    
    
    public class TestClass
    {
        [Inject]
        private SomeDependency sd { get; set; }
    
        public TestClass()
        {
            Console.WriteLine("ctor");
            Console.WriteLine(sd);
        }
    }
    
    public class SomeDependency
    {
    
    }
    
    
    class Program
    {
        static void Main(string[] args)
        {
            object tc = FormatterServices.GetUninitializedObject(typeof(TestClass));
    
            // Get all properties with inject tag
            List pi = typeof(TestClass)
                .GetProperties(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public)
                .Where(info => info.GetCustomAttributes(typeof(InjectAttribute), false).Length > 0).ToList();
    
            // We now happen to know there's only one dependency so we take a shortcut just for the sake of this example and just set value to it without inspecting it
            pi[0].SetValue(tc, new SomeDependency(), null);
    
    
            // Find the right constructor and Invoke it. 
            ConstructorInfo ci = typeof(TestClass).GetConstructors()[0];
            ci.Invoke(tc, null);
    
        }
    }
    

    I am currently working on a hobby project which works like this https://github.com/Jokine/ToolProject/tree/Core

提交回复
热议问题