views:

38

answers:

2

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  A: 

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.

Femaref
But if I set [assembly: InternalsVisibleTo("Microsoft.Practices.Unity")] shouldn't that work?
I doubt it, as Microsoft.Practices.Unity isn't the calling assembly, your container creation is.
Femaref
A: 

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.

Anero
Well that would still mean that both IType1 and Type1 are public doesn't it? What if I don't want expose these outside the library. Isn't there a way to keep them internal and still do dependency injection.
In that case you can make the properties from the FactoryClass internal.I'd seriously consider using InternalsVisibleTo, you can search all over the web for reasons not to use it (similar to the C++ friend concept).
Anero
Hmm.. I cannot implement a public interface and have internal properties. InternalsVisibleTo doesn't seem to work so it's not an option at this time.