我如何在子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>();
}
}
答案 0 :(得分:2)
这真的是错误的做法。认真重新考虑您的容器层次结构,您可能根本不需要层次结构。
然而,如果你已经死定了,你可以假装它。使用引发异常的InjectionFactory重新注册子类型。
childContainer.RegisterType<A>(
new InjectionContructor(c => throw new InvalidOperationException(
"No type A for you!"))));