0

How i can restrict type resolving in child unityContainer ?

E.g

internal interface ITestInterface
{}
public class Test:ITestInterface
{}
class A
{
    public A(ITestInterface testInterface)
    {    
    }
}

class Program
{
    static void Main(string[] args)
    {

        var container = new UnityContainer();

        Test test = new Test();
        container.RegisterInstance<ITestInterface>(test);

        var childContainer = container.CreateChildContainer();
        //shoudl resolved normally
        container.Resolve<A>();
        //should throw exception!
        //because i want restrict resolving ITestInterface instance from parent container!            
        childContainer.Resolve<A>();                       
    }
}
5
  • You want the derived container have it's own set of registrations? So that some classes can only be derived from the parent container? Commented May 13, 2011 at 11:55
  • it not derived container it is child container. It important difference Commented May 13, 2011 at 12:20
  • Yes, I mean child container. Sorry for confusion. So you want the child container to have it's own set of registrations? Commented May 13, 2011 at 12:25
  • by default child container ovveride any registrations and if it not found registration is own set it searches types in parent container.. Commented May 13, 2011 at 12:27
  • i want force my parent container don't resolve certain types in child container. Commented May 13, 2011 at 12:28

1 Answer 1

2

This is really the wrong thing to do. Seriously reconsider your container hierarchies, you may not want a hierarchy at all here.

However, if you're dead set on doing this, you can fake it. Reregister the type in the child with an InjectionFactory that throws an exception.

childContainer.RegisterType<A>(
    new InjectionContructor(c => throw new InvalidOperationException(
        "No type A for you!"))));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.