在业务层,我有3个服务接口(interface)
IUserService
IRoleService
和 IGroupService
和一个验证器接口(interface)IValidator
IValidator 有 3 个实现 - UserValidator
、RoleValidator
、GroupValidator
。
IUserService is implemented by UserService(IValidator userValidator)
IRoleService is implemented by RoleService(IValidator userValidator)
IGroupServiceis implemented by GroupService(IValidator userValidator)
这三个服务都以 IValidator 作为构造参数。
在 web 层,我有 3 个 Controller UserController
接受 IUserService
作为构造函数参数, RoleController
接受 IRoleService
作为构造函数参数,
和 Group Controller 接受 IGroupServiceas
构造函数参数
我的问题:
我如何强制 roleService 获取 RoleValidator
对象和 GroupService
获取 GroupValidator
对象。
我正在使用城堡温莎 3.1
windsorContainer.Register(Component.For<IValidator>()
.ImplementedBy<UserValidator>()
.Named("userValidator")
.LifestyleTransient());
windsorContainer.Register(Component.For<IValidator>()
.ImplementedBy<RoleValidator>()
.Named("roleValidator")
.LifestyleTransient());
windsorContainer.Register(Component.For<IValidator>()
.ImplementedBy<GroupValidator>()
.Named("groupValidator")
.LifestyleTransient());
我在注册 userValidator 时使用了 IsFallback()
,但所有 3 个服务都获得了 roleValidator 对象。
最佳答案
Windsor 允许您使用 Service Overrides 执行此操作.
更新
给定以下设置:
public interface IMyService
{
}
public class Concrete1 : IMyService
{
}
public class Concrete2 : IMyService
{
}
public class ClassA
{
private IMyService service;
public ClassA(IMyService service)
{
this.service = service;
}
}
public class ClassB
{
private IMyService service;
public ClassB(IMyService service)
{
this.service = service;
}
}
下面是如何使用 DependsOn
来选择 ClassA
和 的“服务”参数使用哪个
构造函数:IMyService
实现B类
var container = new WindsorContainer();
container.Register(
Component.For<IMyService>().ImplementedBy<Concrete1>().Named("C1"),
Component.For<IMyService>().ImplementedBy<Concrete2>().Named("C2"),
Component.For<ClassA>().DependsOn(Dependency.OnComponent("service", "C1")),
Component.For<ClassB>().DependsOn(Dependency.OnComponent("service", "C2"))
);
关于c# - 注册不同的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14164538/