简体   繁体   English

将实例传递给 ASP.NET Core 依赖注入的缺点

[英]Drawbacks to Passing an Instance to ASP.NET Core Dependency Injection

I have a class that needs a connection string as a parameter to its constructor:我有一个类需要一个连接字符串作为其构造函数的参数:

public class MyClassHere
{
     private string connectionString;

     public MyClassHere(string connectionString)
     {
        this.connectionString = connectionString;
     }
}

I have added that class as a singleton to my service like this:我已将该类作为单例添加到我的服务中,如下所示:

services.AddSingleton<MyClassHere>();

Clearly this does not work, because it takes a string in the constructor.显然这不起作用,因为它在构造函数中需要一个字符串。

I have seen examples that say do this:我见过这样说的例子:

services.AddSingleton<MyClassHere>(new MyClassHere("Some Connnection String"));

But I have also read vague things say that when you do this the dependency injection system will not clean up your objects for you.但我也读过一些模糊的说法,当你这样做时,依赖注入系统不会为你清理你的对象。

What (if any) are the drawbacks to passing an instance into the dependency injection system (rather than just letting it make it for you)?将实例传递到依赖注入系统(而不仅仅是让它为您制作)有什么(如果有的话)缺点?

One drawback of doing this is that if the constructor of MyClassHere were to change, you'd have to update the usage of it in your DI registration.这样做的一个缺点是,如果要更改MyClassHere的构造函数,则必须在 DI 注册中更新它的用法。 Which may or may not be trivial depending on how it's used.取决于它的使用方式,这可能是也可能不是微不足道的。

Regardless, one way to handle this scenario in .NET Core while maintaining all of the benefits of dependency injection is by using the Options pattern .无论如何,在 .NET Core 中处理这种情况同时保持依赖注入的所有好处的一种方法是使用选项模式


Here's what that might look like given your example:根据您的示例,这可能看起来像这样:

public class MyOptions
{
    public string ConnectionString { get; set; }
}

public class MyClassHere
{
    private readonly string _connectionString;

    public MyClassHere(IOptions<MyOptions> options)
    {
        _connectionString = options.Value.ConnectionString;
    }

    public void Foo() => Console.WriteLine(_connectionString);
}

And here's an example of the registration:这是一个注册示例:

static void Main(string[] args)
{
    var myClass = new ServiceCollection()
        .Configure<MyOptions>(o =>
        {
            o.ConnectionString = "bar";
        })
        .AddSingleton<MyClassHere>()
        .BuildServiceProvider()
        .GetService<MyClassHere>();

    myClass.Foo();

    Console.ReadLine();
}

Which outputs "bar" as expected.按预期输出“bar”。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM