Castle Windsor with Multiple Constructors

旧时模样 提交于 2019-12-01 17:04:19

This might be regarded as a bug (and indeed for cases like this it's fixable) but it's kindof a by-design feature.

Windsor tries to match the greediest constructor (one with the most parameters) it can satisfy.

However in your case, there are two constructors that have the greatest number of parameters (of one), so Windsor just picks the first, where what the "first" means is undefined.

indeed if you switch the order of your constructors in your source code your code will start working, although it's a hack, relying on undocumented behavior and don't do it.

Let's go back to where we started shall we?

I said Windsor is confused because there's no single greediest constructor it can satisfy.

Quick and well-defined fix would be to add a fake parameter to one of th constructors so that they have different numbers of parameters:

public class UserRepository : IUserRepository {
    public UserRepository(IObjectContext objectContext, object fakeIgnoreMe)  {
        // Check that the supplied arguments are valid.
        Validate.Arguments.IsNotNull(objectContext, "objectContext");
        // ignoring fake additional argument
        // Initialize the local fields.
        ObjectContext = objectContext;
    }

    public UserRepository(IObjectContextFactory factory) 
        : this(factory.CreateObjectContext()) { 
    }

    // -----------------------------------------------
    // Insert methods and properties...
    // -----------------------------------------------
}

Please report this issue to Castle users list or straight to issue tracker so that it will get fixed.

As of Windsor 3.2.x

If the attribute Castle.Core.DoNotSelectAttribute is applied to a constructor, it will not be selected, notwithstanding any other criteria.

public class UserRepository : IUserRepository
{
    [DoNotSelect] // This constructor will be ignored by Windsor
    public UserRepository(IObjectContext objectContext)
    {
        // ...
    }

    public UserRepository(IObjectContextFactory factory)
        : this(factory.CreateObjectContext()) {}
}

Reference: https://github.com/castleproject/Windsor/blob/86696989a7698c45b992eb6e7a67b765b48108b0/docs/how-constructor-is-selected.md

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!