如何在 asp.net web api 2 中实现依赖注入

How to implement dependency injection in asp.net web api 2

我想在我的 .net web api 项目中使用这个 nuget 包: https://github.com/Elfocrash/Cosmonaut/tree/885a98151be242516ec57cd94da1747b72588788

我的想法是在 4.6.1 中使用来自 .net web api 的 nuget 包,但是这个包以 netstandard 2 为目标。所以我无法安装 nuget 包。

最后,我下载了源代码并在 .net 4.6.1 中创建了一个新的 class 库,并且编译完美。

然后我从 .net web api 添加了对这个库的引用。

但是我对 serviceCollection 有疑问,因为它不存在。 我如何使用 serviceCollection?

// [Authorize]
    public class TenantController : ApiController
    {
        private  CosmosStoreSettings cosmosSettings;

        public TenantController()
        {

            cosmosSettings = new CosmosStoreSettings(ConfigurationManager.AppSettings["database"].ToString(), 
                ConfigurationManager.AppSettings["endpoint"].ToString(), 
                ConfigurationManager.AppSettings["authKey"].ToString());

            serviceCollection.AddCosmosStore<Book>(cosmosSettings);

        }

The name 'serviceCollection' does not exist in the current context

我很清楚这意味着什么,但我不确定如何在这个项目上实现 DI

您正在使用的库使用 Microsoft.Extensions.DependencyInjection NuGet 包,其中包含 ASP.NET Core 使用的依赖注入框架。虽然它不依赖于 ASP.NET Core(甚至不依赖于 .NET Core),但鉴于您使用的是 ASP.NET Web API 2,我建议您保持简单并创建ComosStore<T>附近的工厂:

public static class CosmosStoreFactory 
{
    private static CosmosStoreSettings _settings = new CosmosStoreSettings("<<databaseName>>", "<<cosmosUri>>", "<<authkey>>");

    public static ICosmosStore<T> CreateForEntity<T>() where T: class
    {
         return new CosmosStore<T>(_settings);
    }
}

我已经使用 WebAPI2Get the GITHUB code here! 实现了 依赖注入 只需下载应用程序并浏览代码即可。这是一个非常简单的 CRUD 应用程序。请浏览 README.md 文件。

有几个可用的依赖注入容器: 我用过Unity

添加 Unity 的步骤。 1.Add 库 Unity.AspNet.WebAp 到您的应用程序。 2.UnityConfig.cs 文件将添加到您的 APP_START 文件夹。

然后按照我在示例应用程序中完成的代码进行操作。