简体   繁体   English

我们可以注入具有不同变量的相同 class 的多个实例吗?

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

Can we inject multiple instances of the same class with different variables?我们可以注入具有不同变量的相同 class 的多个实例吗?

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.使用.TryAddScoped您只有一个类型实例,如果您使用.AddScoped您可以添加多个实例并在 controller 中接收一个 IEnumerable。

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: Controller:

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

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

相关问题 Autofac如何帮助您同时在一个现有类中注入一个类/接口的多个实例 - How Autofac helps You to inject multiple instances of a class/interface in an existing class at the same time 将多个不同的实例切换到一个类中 - Switch with multiple different instances into a class Unity中的序列化示例; 具有相同类别的不同实例 - Example of Serialization in Unity; with different instances of the same class 如何在Asp.Net Core DI上注入具有不同生命周期的同一个类? - How can I inject same class with different Life Cycles on Asp.Net Core DI? 同一进程的多个实例记录在不同的文件上 - Multiple instances of same process logging on different files 同一订户在不同计算机上的多个实例 - Multiple instances of the same subscriber on different machines 如何将变量的不同值分配给同一对象的不同实例? - How to assign different values of variables to different instances of the same object? 对同一类的多个实例的控制反转 - Inversion of Control for multiple instances of same class 多个类实例引发同一事件 - Multiple class instances raising same event Simple Injector可以使用不同的构造函数参数注册相同类型的多个实例吗? - Can Simple Injector register multiple instances of same type using different constructor parameters?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM