void
void

Reputation: 1367

Unity constrainting type\instance resolving in child container

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>();                       
    }
}

Upvotes: 0

Views: 1198

Answers (1)

Chris Tavares
Chris Tavares

Reputation: 30401

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!"))));

Upvotes: 2

Related Questions