构造函数不能自称

Ton*_*ony 3 .net c# dependency-injection castle-windsor

我使用Castle Windsor作为DI机制,我被困在这里.我使用构造函数注入类型,它工作正常.

但是,当我声明一些其他类的构造函数时,我需要调用默认构造函数,在那里发生DI魔术.

所以,我有以下代码:

private readonly IUserService UserService = null;

public CustomAccessAttribute(IUserService userService)
{
    this.UserService = userService;
}

public CustomAccessAttribute(bool someParam) : this() //here I'd like to call the above constructor
{
    ....           
}
Run Code Online (Sandbox Code Playgroud)

但我得到了错误

构造函数'CustomAccessAttribute.CustomAccessAttribute(bool)'无法调用自身

我不想把userService对象放在this()调用中,因为DI容器应该这样做.那么,我该如何解决这个错误呢?

Yuv*_*kov 7

我想你是以错误的方式攻击这个.

如果希望DI容器选择正确的重载,则必须提供要接收的所有参数.接受一个bool只会无济于事,因为你实际上也需要IUserService接口.它不会让自己出现在任何地方.您的DI需要知道它存在并且必须传递给适当的构造函数.

你需要的是:

private readonly IUserService UserService = null;
public CustomAccessAttribute(IUserService userService)
{
    this.UserService = userService;
}

public CustomAccessAttribute(IUserService userService, bool someParam) : this(userService) 
{         
}
Run Code Online (Sandbox Code Playgroud)

虽然,您通常希望使构造函数向外链接,从最少的参数到最多.所以也许你想做:

private readonly IUserService UserService = null;
public CustomAccessAttribute(IUserService userService) : this(userService, false)
{
}

public CustomAccessAttribute(IUserService userService, bool someParam)
{  
    this.UserService = userService;
}
Run Code Online (Sandbox Code Playgroud)

编辑:

如果bool你想传递给你的构造函数在注入时不可用,那么构造函数注入可能根本不可能.也许更合适的方法是将它设置为属性,可以在可用时设置bool,或者在一切可用时为您创建类实例的工厂模式.