.NET 4.0 最新的 autofac 版本和最新的 C# 驱动程序
我们正在将 Autofac DI 容器集成到我们的 MongoDB 应用程序中,事情进展顺利,但有一个例外可能是我的 BUD(设备上的坏用户)。既然我的谷歌赋失败了,我想我会利用你的智慧。
问题是我们希望支持基于接口的多态性,并保持数据层之外的所有交互不知道任何创建的实体类型。下面是一个简化的例子。
///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 有更好的支持(我听说即将推出)。谢谢你的帮助。