Unity约束类型\实例在子容器中解析
我如何限制子 unityContainer 中的类型解析?
例如
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>();
}
}
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>();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这确实是错误的做法。认真重新考虑您的容器层次结构,您可能根本不需要层次结构。
然而,如果你铁了心要这样做,你可以假装它。使用抛出异常的 InjectionFactory 重新注册子级中的类型。
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.