集成Autofac和MongoDB C#驱动程序

时间:2012-09-04 09:59:18

标签: c# mongodb autofac mongodb-.net-driver

.NET 4.0最新的autofac版本和最新的C#驱动程序

我们正在将Autofac DI容器集成到我们的MongoDB应用程序中,并且事情一直在游动,有一个例外,我可能是BUD(设备上的坏用户)。由于我的Google Fu让我失望,我想我会利用你的智慧。

问题在于我们希望支持基于接口的多态性,并保持数据层之外的所有交互都不知道任何混合实体类型。简化示例如下。

///Datastore wrapper
public interfaces IDataStore
{
    T Get<T>(string key);
    IQueryable<T> GetCollection(string key)        
}

public interface ITransaction
{
    public string key {get;}
    public double value {get;}
}

public interface IStockTransaction: ITransaction
{
    public string Symbol{get;}
}

public class StockTransaction: IStockTransaction
{
    public string key {get;}
    public double value {get;}
    public double price {get;}
}

//The goal is to get this test to pass. 
[TestMethod()]
public void PolyMorphicTest()
{
    //Wrapper around on Autofac.
    var container = new ContainerConfiguration();
    var target= container.Resolve<IDataStore>();
    //Assume a stock transaction with a key named foo has been saved. 
    var type = target.Get<IStockTransaction>("foo");
    Assert.IsInstanceOfType(type,typeof(StockSymbol));
} 

我尝试了各种类型的Autofac注册方法,但由于我完全没有Mongo类型的激活链(例如像MongoDatabase.GetCollection()这样的调用),它们似乎都爆炸了。有没有办法使用Autofac来控制Mongo类型的激活链?对于我们想要的工作方法,我需要找到一种方法来使用Autofac来替换由上层代码传递给已解析类型的类型参数T.然后我们应该能够依靠方差将其作为传入类型返回。

T Get<T>(string key) //T Arrives as IStockTransaction 
{
    var coll = Database.GetCollection<T>(T.FullName).AsQueryAble<T>();
    /*T is now the concrete type StockTransaction so that Mongo can query properly.*/

    /* perform a linq query here against the IQueryable. */ 

    return  (T) ((from tmp in coll 
        where tmp.key == " ").FirstOrDefault());  
}

IQueryable<T> GetCollection<T>(string key) //T Arrives as IStockTransaction 
{        
    /*Attempting to Find the Mongo collection using the interface type will lead to Mongo
    serialization errors so we need to change the interface type to the concrete type that we 
    have registered in Autofac or have stashed off manually somewhere before this call. Ideally 
    this would be done with a simple resolve call against Autofac so that if our concrete types 
    change, all of this would still work. */

    var coll = Database.GetCollection<T>(T.FullName).AsQueryAble<T>(); 

    /*Here we would rely on C# 4.0 variance to allow us to cast back to the interface type.*/

    return  (T) coll.FirstOrDefault();  
}

对不起,很长的帖子 - 会感激任何想法。很高兴澄清问题是否不清楚。现在我倾向于攻击MongoDriver,以便Autofac成为解决方案的组成部分。我们的另一个选择是等到驱动程序更好地支持接口和DI(我听到即将到来)。谢谢你的帮助。

0 个答案:

没有答案