[英]How do I use DI on asp.net web api project not .net core
以下文档显示了如何为.net核心项目配置cosmonaut。
https://github.com/Elfocrash/Cosmonaut
Registering the CosmosStores in ServiceCollection for DI support
var cosmosSettings = new CosmosStoreSettings("<<databaseName>>", "<<cosmosUri>>", "<<authkey>>");
serviceCollection.AddCosmosStore<Book>(cosmosSettings);
//or just by using the Action extension
serviceCollection.AddCosmosStore<Book>("<<databaseName>>", "<<cosmosUri>>", "<<authkey>>", settings =>
{
settings.ConnectionPolicy = connectionPolicy;
settings.DefaultCollectionThroughput = 5000;
settings.IndexingPolicy = new IndexingPolicy(new RangeIndex(DataType.Number, -1),
new RangeIndex(DataType.String, -1));
});
我如何处理旧的webpi项目?
Web Api 2并没有开箱即用的依赖项注入,您可以使用Autofac和Ninject等第三方依赖项注入包,或者如果您根本不想使用依赖项注入,也可以创建Cosmonaut的singleton类以供使用。 。
注意:根据他们的文档 ,Cosmonaut实例应用作每个实体的单例实例。
更新
通用Singleton类的实现,其中T是您要查询其实例的实体的类型,
public sealed class CosmosStoreSingleton<T>
{
private static ICosmosStore<T> instance = null;
public static ICosmosStore<T> Instance
{
get
{
if (instance==null)
{
var cosmosSettings = new CosmosStoreSettings("<<databaseName>>", "<<cosmosUri>>", "<<authkey>>");
instance = new CosmosStore<T>(cosmosSettings);
}
return instance;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.