Dotnet核心依赖注入参数

Hus*_*ain 3 c# dependency-injection .net-core

假设我有班级

public class Entity : IEntity {
    public Entity(IDependency dep, string url)
    {
        //...
    }
}

public class Dependency : IDependency {
    //...
}
Run Code Online (Sandbox Code Playgroud)

现在当我想使用依赖注入时,我可以做类似的事情:

IServiceCollection serviceCollection = new ServiceCollection();
serviceCollection.AddScoped<IDependency, Dependency>();
serviceCollection.AddScoped<IEntity, Entity>(); // how to inject the url
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,问题在于我不知道如何注入url值(例如" https://google.com/ ").我知道结构图提供了命名参数及其值.

有没有办法Entity在使用DI作为依赖项时将字符串注入构造函数?

Nko*_*osi 12

您需要使用AddScoped重载提供实现工厂函数来配置如何初始化实现.

IServiceCollection serviceCollection = new ServiceCollection();
serviceCollection.AddScoped<IDependency, Dependency>();
serviceCollection.AddScoped<IEntity>(provider => 
    new Entity(provider.GetService<IDependency>(), "https://example.com/")
);
Run Code Online (Sandbox Code Playgroud)

请注意提供程序如何用于解析其他依赖项.

因此,现在当IEntity请求实现时,将调用实现工厂,并且还可以使用任何已配置的依赖项解决实现.