Unity 1.2 Dependency injection of internal types

孤街浪徒 提交于 2019-12-24 07:02:12

问题


I have a facade in a library that exposes some complex functionality through a simple interface. My question is how do I do dependency injection for the internal types used in the facade. Let's say my C# library code looks like -

public class XYZfacade:IFacade
{
    [Dependency]
    internal IType1 type1
    {
        get;
        set;
    }
    [Dependency]
    internal IType2 type2
    {
        get;
        set;
    }
    public string SomeFunction()
    {
        return type1.someString();
    }
}

internal class TypeA
{
....
}
internal class TypeB
{
....
}

And my website code is like -

 IUnityContainer container = new UnityContainer();
 container.RegisterType<IType1, TypeA>();
 container.RegisterType<IType2, TypeB>();
 container.RegisterType<IFacade, XYZFacade>();
 ...
 ...
 IFacade facade = container.Resolve<IFacade>();

Here facade.SomeFunction() throws an exception because facade.type1 and facade.type2 are null. Any help is appreciated.


回答1:


Injecting internal classes is not a recommended practice.

I'd create a public factory class in the assembly which the internal implementations are declared which can be used to instantiate those types:

public class FactoryClass
{
   public IType1 FirstDependency
   {
     get
     {
       return new Type1();
     }
   }

   public IType2 SecondDependency
   {
     get
     {
       return new Type2();
     }
   }
 }

And the dependency in XYZFacade would be with the FactoryClass class:

public class XYZfacade:IFacade
{
   [Dependency]
   public FactoryClass Factory
   {
      get;
      set;
   }
}

If you want to make it testable create an interface for the FactoryClass.




回答2:


If the container creation code is outside the assembly of the internal types, Unity can't see and create them and thus can't inject the dependecies.



来源:https://stackoverflow.com/questions/3010612/unity-1-2-dependency-injection-of-internal-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!