简体   繁体   English

.NET Core DI 没有构造函数参数

[英].NET Core DI without constructor arguments

Until now, I have used the Unity IOC container to resolve dependencies, which works just fine.到目前为止,我一直使用 Unity IOC 容器来解决依赖关系,效果很好。 With the Unity DI, I normally resolve instances in the following way:使用 Unity DI,我通常通过以下方式解析实例:

Public class TestClass {
    public TestClass()
    {
        var instance = IOC.resolve<InterfaceClassToResolve>();
    }
}

This works great, but seeing that .net core now provides me with an out of the box DI container, I would much rather like to use that - There is just one problem compared to the Unity IOC, namely that it is injected as a constructor argument, and not resolved like the example above.这很好用,但看到 .net 核心现在为我提供了一个开箱即用的 DI 容器,我更愿意使用它 - 与 Unity IOC 相比只有一个问题,即它作为构造函数注入争论,而不是像上面的例子那样解决。

In most cases, I figured that it forces me to chain my dependencies throughout multiple classes, instead of just resolving my dependency in the classes that actually needs them.在大多数情况下,我认为它迫使我在多个类中链接我的依赖项,而不是仅仅在实际需要它们的类中解决我的依赖项。

I have been looking at ways to solve this, and as far as I can see, the only option is to do something like this:我一直在寻找解决这个问题的方法,据我所知,唯一的选择是做这样的事情:

Public class TestClass {
    public TestClass(IServiceProvider serviceProvider)
    {
        var instance = serviceProvider.GetService<InterfaceClassToResolve>();
    }
}

And then we are back to square one again...然后我们又回到了原点……

Therefore, am I missing some of the functionality behind the .net core IOC, or is there some secret sauce to why most examples wants me use the .net core IOC via constructor arguments?因此,我是否错过了 .net 核心 IOC 背后的某些功能,或者为什么大多数示例希望我通过构造函数参数使用 .net 核心 IOC?

As already commented, Service Locator pattern is not the best method and considered an anti-pattern.正如已经评论过的,服务定位器模式不是最好的方法,被认为是一种反模式。 I understand the necessity, though, of finding a way to easily convert existing code to the out-of-the-box DI system without going mad.不过,我理解找到一种方法可以轻松地将现有代码转换为开箱即用的 DI 系统而不会发疯的必要性。 I therefore suggest you to do something like this:因此,我建议您执行以下操作:

1) Startup.cs 1)Startup.cs

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<DatabaseContext>(
            options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

        // other services configuration here

        // IMPORTANT: This should be the last line of ConfigureServices!
        IOC.CurrentProvider = services.BuildServiceProvider();
    }
...

2) IOC.cs 2) 国际奥委会.cs

public class IOC
{
    public static IServiceProvider CurrentProvider { get; internal set; }

    public static T resolve<T>()
    {
        return CurrentProvider.GetService<T>();
    }
}

This should allow you to use dotnet core DI with existing service locator code based on Unity, with minimal fixes (basically just some using declarations to be fixed), as long as you solemnly promise to refactor your code as soon as possible to get rid of all that Service Locator code :D这应该允许您将 dotnet core DI 与基于 Unity 的现有服务定位器代码一起使用,只需最少的修复(基本上只是一些需要修复的 using 声明),只要您郑重承诺尽快重构您的代码以摆脱所有服务定位器代码:D

You can use DI without constructors like:您可以在没有构造函数的情况下使用 DI,例如:

On the ConfigureServicesConfigureServices

services.AddSingleton<YourClass>()

Then inject it like this:然后像这样注入它:

private YourClass YourClass
{
    get
    {
        return this.serviceProvider.GetRequiredService<YourClass>();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 没有DI登录.NET Core? - Logging in .NET Core without DI? IHostEnvironment 和启动构造函数中没有 DI .NET Core 3+ - IHostEnvironment and no DI in Startup constructor .NET Core 3+ .NET Core DI,将参数传递给构造函数的方法 - .NET Core DI, ways of passing parameters to constructor 带有参数和 DI 的 ASP.Net Core 过滤器 - ASP.Net Core filters with arguments and DI MassTransit和.NET Core DI - 如何使用无参数构造函数解决依赖关系? - MassTransit and .NET Core DI - how to resolve dependencies with parameterless constructor? .Net Core DI - 通过构造函数注入与使用 scope 解析 - .Net Core DI - inject via constructor vs resolve using scope .NET Core 2和DI - 在构造函数中使用appsettings.json中的值? - .NET Core 2 & DI - use values from appsettings.json in the constructor? 在 .NET Core 中使用不同的构造函数参数(DI 和非 DI)注册多个 IHostedService 实例 - Register multiple instances of IHostedService with different constructor parameters (DI and non-DI) in .NET Core 没有用于ASP.NET MVC的DI容器的控制器的构造函数参数 - Constructor parameters for controllers without a DI container for ASP.NET MVC .NET Core的可选构造函数注入参数 - Optional constructor injection arguments with .NET Core
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM