开发者

Unity constrainting type\instance resolving in child container

开发者 https://www.devze.com 2023-03-05 10:37 出处:网络
How i can restrict type resolving in child unityContainer ? E.g internal interface ITestInterface {} public class Test:ITestInterface

How i can restrict type resolving in child unityContainer ?

E.g

internal interface ITestInterface
{}
public class Test:ITestInterface
{}
class A
{
    public A(ITestInterface testInterfac开发者_StackOverflow中文版e)
    {    
    }
}

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


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

精彩评论

暂无评论...
验证码 换一张
取 消