我想创建一个容器,它允许解析 ISomeService,但不允许解析 ISomeOtherService。尽管我对 ISomeService 的注册依赖于 ISomeOtherService。
这有意义吗?
public interface ISomeService {}
public interface ISomeOtherService {}
public class SomeService : ISomeService
{
public SomeService(ISomeOtherService someOtherService) {}
}
public class SomeOtherService : ISomeOtherService {}
我想要的这个容器会为 ISomeService 解析 SomeService,但如果我尝试解析 ISomeOtherService 或 SomeOtherService,它将失败。
这是糟糕的设计吗?
那么,一些上下文......我有将由各种开发人员开发的 ASP.Net MVC Controller 。这些 Controller 应该可以访问像 ISomeService 这样的应用程序服务,但不能访问它们的依赖项。我想避免必须对所有这些服务进行代码审查,以确保开发人员没有违反架构设计。他们应该能够获得对 ISomeService 的引用,但 ISomeOtherService 是一个数据库存储库,他们不应该直接处理它,但 ISomeService 确实需要这个引用。
我不介意希望在解析过程中(它是一个 ASP.NET MVC 应用程序,我已经有一个用于创建 Controller 的扩展点)所以我可以看看正在解析的 Controller ,看看它的依赖关系并确保它们在白名单上,但我不知道如何轻松评估与温莎的依赖关系。或者,我是否只需要通过查看构造函数参数自己完成?
最佳答案
您可以使用 SubDependencyResolver 检查。请看下面的代码:
public class SubDependencyResolver : ISubDependencyResolver
{
public bool CanResolve(CreationContext context, ISubDependencyResolver contextHandlerResolver, ComponentModel model,
DependencyModel dependency)
{
// If not an ISomeotherComponent or SomeOtherComponent is resolved ignore.
if (dependency.TargetType != typeof (ISomeOtherComponent) && dependency.TargetType != typeof (SomeOtherComponent)) return false;
// check if we are resolving for SomeComponent
if (model.Implementation == typeof (SomeComponent)) return false;
// We are resolving for a different component then SomeComponent.
Debug.Assert(false);
return false;
}
public object Resolve(CreationContext context, ISubDependencyResolver contextHandlerResolver, ComponentModel model,
DependencyModel dependency)
{
// We will never actually resolve the component, but always use the standard SubDependencyResolver, as Can resolve always returns false;
return null;
}
}
class Program
{
static void Main(string[] args)
{
var container = new WindsorContainer();
container.Kernel.Resolver.AddSubResolver(new SubDependencyResolver());
container.Register(
Component.For<ISomeOtherComponent>().ImplementedBy<SomeOtherComponent>(),
Component.For<ISomeComponent>().ImplementedBy<SomeComponent>(),
Component.For<Legal>()
// Component.For<Illegal>() uncommenting this line will assert.
);
}
}
public interface ISomeComponent
{
}
public interface ISomeOtherComponent
{
}
public class SomeComponent : ISomeComponent
{
public SomeComponent(ISomeOtherComponent someOtherComponent)
{
}
}
public class SomeOtherComponent : ISomeOtherComponent
{
}
public class Legal
{
public Legal(ISomeComponent component)
{
}
}
public class Illegal
{
public Illegal(ISomeOtherComponent component)
{
}
}
关于c# - 限制 Windsor 容器解析基于的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20893603/