简体   繁体   中英

Can we inject multiple instances of the same class with different variables?

Can we inject multiple instances of the same class with different variables?

services.TryAddScoped<ISomeClass>(sp =>
{
    return new SomeClass(1);
});

services.TryAddScoped<ISomeClass>(sp =>
{
    return new SomeClass(2);
});

And someway pull the needed one into seperate controllers.

With .TryAddScoped you have only one instance for type, if you use .AddScoped you can add multiple instances and receive a IEnumerable in your controller.

If you need named instances, I have created my custom solution:

public class NamedService<T>
{
    public string Name { get; set; }
    public T Service { get; set; }

    public NamedService(string name, T service)
    {
        Name = name;
        Service = service;
    }
}

Extension methods:

public static T GetService<T>(this IServiceProvider serviceProvider, string name = null) where T : class
{
    if (name != null)
    {
        var list = serviceProvider.GetServices<NamedService<T>>();
        return list.FirstOrDefault(n => n.Name == name)?.Service;
    }
    return serviceProvider.GetService<T>();
}

public static IServiceCollection AddScoped<T>(this IServiceCollection services, string name, Func<IServiceProvider, T> factory)
{
    return services.AddScoped(sp => new NamedService<T>(name, factory(sp)));
}

Usage:

Services.AddScoped("some1", s => new SomeClass(1));
Services.AddScoped("some2", s => new SomeClass(2));

Controller:

public SomeController(IServiceProvider serviceProvider)
{
    var someInstance = serviceProvider.GetService<ISomeClass>("some1");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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