How do I use DI on asp.net web api project not .net core

142 views Asked by At

The following documentation shows how to configure cosmonaut for a .net core project.

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));
});

How do I do for an old webpi project?

1

There are 1 answers

3
Riaz Raza On BEST ANSWER

Web Api 2 doesn't come with out of box dependency injection, you can use 3rd party dependency injection packages like Autofac and Ninject etc, or you can create Cosmonaut's singleton class for use too if you don't want to use dependency injection at all.

Note: As per their docs, Cosmonaut instance should be used as singleton instances per entity.

UPDATE

Implementation of a generic Singleton class where T is the type of entity you are asking for the instance of,

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;
        }
    }
}