Unity InjectionConstructor for multiparam constructor overriding only single one

前端 未结 3 2087
长发绾君心
长发绾君心 2021-01-03 17:35

I have a class with constructor like this:

public class Bar
{
    public Bar(IFoo foo, IFoo2 foo2, IFoo3 foo3, IFooN fooN, String text)
    {

    }
}
         


        
3条回答
  •  北海茫月
    2021-01-03 18:06

    I used to do that as described in the answer above (that's using InjectionConstructor). The problem with that is that if the signature of the constructor is changed but InjectionConstructor is not updated, then we will know that only at run time. I think that there is a cleaner way to do that and without getting deep into details of the signature of the constructor. Here is how:

    public interface IBar
    {
        void DoSomethingWithBar();
    }
    
    public interface IMyStringPrameterForBar
    {
        string Value { get; }
    }
    
    public class MyStringPrameterForBar : IMyStringPrameterForBar
    {
        public string Value { get; }
        public MyStringPrameterForBar(string value) => Value = value; 
    }
    
    public class Bar : IBar
    {
        public Bar(IFoo foo, IFoo2 foo2, IFoo3 foo3, IFooN fooN, IMyStringPrameterForBar text)
        {
        }
    
        public void DoSomethingWithBar() {}
    }
    

    Then when registering interfaces, just add:

    unity.RegisterType();
    unity.RegisterType();
    unity.RegisterType();
    unity.RegisterInstance(new MyStrignPrameterForBar("123"));
    unity.RegisterType();
    

    That's all. if tomorrow Bar needs to take more or less parameters, then after adding or removing extra Foo Unity will still automatically construct Bar.

    PS I don't think that interface IMyStringPrameterForBar is actually required. However, I prefer to see only interfaces in Unity registrations because it is much easier to twist them around during tests and/or for any other purpose.

提交回复
热议问题