Unity 1.2 Dependency injection of internal types

2019-08-14 09:01发布

问题:

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.