Unity framework DependencyAttribute only works for public properties?

前端 未结 8 1210
小鲜肉
小鲜肉 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

    Based on Kent B's answer, I changed to use constructor injection, which does work for public classes. However the root issue still exists, where anything you ever want to assign or have assigned by Unity has to be public. This includes the classes themselves.

    New unit test:

        [TestFixture]
    public class UnityFixture
    {
        [Test]
        public void UnityCanSetInternalDependency()
        {
            UnityContainer container = new UnityContainer();
            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;
        }
    
        private TheDep _Dep;
            internal TheDep dep
            {
                get { return _Dep; }
            }
    }
    
    internal class TheDep
    {
    }
    }
    

    With the assembly attributes:

    [assembly: InternalsVisibleTo("Microsoft.Practices.Unity")]
    [assembly: InternalsVisibleTo("Microsoft.Practices.Unity.Configuration")]
    [assembly: InternalsVisibleTo("Microsoft.Practices.ObjectBuilder2")]
    

    Fails with the error:

    The type HasInternalDep does not have an accessible constructor.
    at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, String name)
    

    So overall it seems that if you want to use Unity, you basically just have to blanket mark everything public. Really ugly for a utility/library .dll...

提交回复
热议问题