如何在 asp.net web api 项目而不是 .net core 上使用 DI

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 没有开箱即用的依赖注入,您可以使用 3rd 方依赖注入包,如 Autofac 和 Ninject 等,或者您可以创建 Cosmonaut 的单例 class 如果你根本不想使用依赖注入,也可以使用。

注意:根据他们的 docs,Cosmonaut 实例应用作每个实体的单例实例。

更新

通用单例的实现class,其中 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;
        }
    }
}