2

在业务层,我有 3 个服务接口 IUserService IRoleServiceIGroupService

一个验证器接口 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 个控制器作为构造函数参数,UserController作为构造函数参数,组控制器作为构造函数参数IUserServiceRoleControllerIRoleServiceIGroupServiceas

我的问题: 我如何强制 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());

IsFallback()在注册 userValidator 时使用,但所有 3 个服务都获得了 roleValidator 对象。

4

1 回答 1

1

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来选择IMyService“服务”参数ClassAClassB构造函数使用的实现:

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"))
    );
于 2013-01-04T22:07:57.937 回答