MongoCollectionFinder <t>:ICollectionFinder <mongocollection <t>&gt;如何使用Windsor Castle注册此组件?</mongocollection <t> </t>

时间:2015-02-21 07:23:39

标签: dependency-injection castle-windsor ioc-container

public class MongoCollectionFinder<T> :     ICollectionFinder<MongoCollection<T>> 
{
    private readonly IDatabaseContext<MongoDatabase> _databaseContext;

    public MongoCollectionFinder(IDatabaseContext<MongoDatabase> databaseContext)
    {
        this._databaseContext = databaseContext;
    }

    /// <summary>
    /// Find collection with specified name from database
    /// </summary>
    /// <param name="collectionName"></param>
    /// <returns></returns>
    public MongoCollection<T> FindCollection(string collectionName)
    {
        var database = _databaseContext.GetDatabase();
        return database.GetCollection<T>(collectionName);
    }

}

我在安装程序中使用此行注册上面

container.Register(Component.For(typeof(ICollectionFinder<>)).ImplementedBy(typeof(MongoCollectionFinder<>)).LifestyleScoped());

但它正在抛出此异常

  

{&#34;类型的对象   &#39; {MongoCollectionFinder {1}} 1 [应用]]&#39;   无法转换为类型   &#39; {ICollectionFinder {1}} 1 [应用]]&#39;&#34;}

1 个答案:

答案 0 :(得分:0)

您正在为未实现的接口注册组件。

这可以看作如下。使用此处显示的注册行,Windsor(3.3)似乎注册正常。但是,如果您致电Resolve<xxx>(),您将获得例外:

Unable to cast object of type 'MongoCollectionFinder`1[xxx]' to type 'ICollectionFinder`1[xxx]'.

哪个是对的。 MongoCollectionFinder<xxx>未实施ICollectionFinder<xxx>,它实施ICollectionFinder<MongoCollection<xxx>>

如果您致电Resolve<MongoCollection<xxx>>(),您将收到以下例外情况:

Unable to cast object of type 'MongoCollectionFinder`1[MongoCollection`1[xxx]]' to type 'ICollectionFinder`1[MongoCollection`1[xxx]]

这又是正确的。 MongoCollectionFinder<MongoCollection<xxx>>未实施ICollectionFinder<MongoCollection<xxx>>,它实施ICollectionFinder<MongoCollection<MongoCollection<xxx>>>