Unity framework DependencyAttribute only works for public properties?

前端 未结 8 1206
小鲜肉
小鲜肉 2021-02-14 17:31

I was trying to clean up some accessability stuff in my code, and inadvertently broke Unity dependency injection. After a while I realized that I marked some public properties t

8条回答
  •  太阳男子
    2021-02-14 17:59

    Well after a lof of poking around in reflector, I figured this out. By default, the code that finds a constructor for constructor injection calls:

    ConstructorInfo[] constructors = typeToConstruct.GetConstructors()
    

    With no BindingFlags, that will only detect public constructors. With some trickery (as in copy/paste from reflector) you can make a UnityContainerExtension that does all the same stuff as the default implementation, but change the call to GetConstructors() to:

    ConstructorInfo[] constructors = typeToConstruct..GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
    

    Then add the extension into the unity container. The implemented extenstion is ~100 lines of code, so I didn't paste it here. If anyone wants it, let me know...

    New working test case. Note that all the Unity created classes are now internal:

    [TestFixture]
    public class UnityFixture
    {
        [Test]
        public void UnityCanSetInternalDependency()
        {
            UnityContainer container = new UnityContainer();
            container.AddNewExtension();
            container.RegisterType();
            container.RegisterType();
    
            var i = container.Resolve();
            Assert.IsNotNull(i);
            Assert.IsNotNull(i.dep);
        }
    }
    
    
    internal class HasInternalDep
    {
        internal HasInternalDep(TheDep dep)
        {
            this.dep = dep;
        }
    
        internal TheDep dep { get; set; }
    }
    
    internal class TheDep
    {
    }
    

    I'm sure I can make an extension to do the same to resolve non-public properties, but that code was a lot more complicated :)

提交回复
热议问题