3

Suppose that I have the class

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

public class Dependency : IDependency {
    //...
}

Now when I want to use dependency injection I can do something like:

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

The problem, as you can see, is that I don't know how to inject a value of url (e.g. "https://google.com/"). I know structure map provides that with naming the parameters and their values.

Is there a way to inject a string into the constructor of Entity while using DI for the dependencies?

Husain
  • 784
  • 1
  • 9
  • 22

2 Answers2

14

You would need to provide an implementation factory function using the AddScoped overload to configure how to initialize the implementation.

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

Note how the provider is used to resolve the other dependency.

So now when ever an IEntity implementation is requested, the implementation factory will be invoked and the implementation resolved also with any configured dependencies.

Nkosi
  • 235,767
  • 35
  • 427
  • 472
4

You can make the Entity take another class dependency that contains a url property.

public Entity(IDependency dep, IConfig config){
   ...
}

public Config:IConfig{
   public string Url {get;set;}
}
alltej
  • 6,787
  • 10
  • 46
  • 87