简体   繁体   English

c#中如何通过反射向依赖容器服务注册服务

[英]How to register services with dependency container services by reflection in c#

I have an interface IProcessor and multiple processors implementing this interface:我有一个接口IProcessor和多个处理器实现这个接口:

Processor1 : IProcessor
Processor2 : IProcessor

I want to inject these processors into a class like: IEnumerable<IProcessor> so that I can run them one by one.我想将这些处理器注入到 class 中,例如: IEnumerable<IProcessor>以便我可以一个一个地运行它们。

I can register these one by one with the microsoft dependency injection container, but I want to do it by reflection so that a newly added processor is registered automatically.我可以用微软依赖注入容器一个一个地注册这些,但我想通过反射来完成,以便自动注册新添加的处理器。

var processorInterface = typeof(IProcessor);

var processors = Assembly.GetExecutingAssembly().GetTypes()
               .Where(t => processorInterface.IsAssignableFrom(t) && t.IsClass && 
               !t.IsAbstract && t.IsPublic);                  

foreach (var processor in processors)
{
    serviceCollection.AddScoped(processor);

    // Below line does not compile of course
    //serviceCollection.AddScoped<IProcessor, processor>());
}

But this doesn't work, I always get an empty list injected.但这不起作用,我总是会注入一个空列表。

I would like to suggest a different approach to this by using attributes.我想通过使用属性来建议一种不同的方法。

Here I created an Attribute which I called InjectableAttribute :在这里,我创建了一个名为InjectableAttribute的属性:

[AttributeUsage(AttributeTargets.Class)]
public class InjectableAttribute: Attribute
{
    public Type ImplementedInterface { get; }
    public DependencyInjectionScope Scope { get; }

    public InjectableAttribute(Type implementedInterface, DependencyInjectionScope scope = DependencyInjectionScope.Singleton)
    {
        ImplementedInterface = implementedInterface;
        Scope = scope;
    }
}

I created this enumeration to specify the scope of the dependency too:我创建了这个枚举来指定依赖项的 scope:

public enum DependencyInjectionScope
{
    Singleton,
    PerDependency,
    Scoped
}

And last, I created this extention method to scan my assembly and inject all the classes that have InjectableAttribute:最后,我创建了这个扩展方法来扫描我的程序集并注入所有具有 InjectableAttribute 的类:

namespace Microsoft.Extensions.DependencyInjection
{
    public static class DependencyInjectionExtensions
    {
        public static void RegisterDependencies(this IServiceCollection services, Assembly assembly)
        {
            var types = assembly
                .ExportedTypes
                .Where(x => x.GetCustomAttributes(typeof(InjectableAttribute), true).Length > 0)
                .ToList();

            for (var i = 0; i < types.Count; i++)
            {
                var currentType = types[i];
                var attributes = (InjectableAttribute[])currentType.GetCustomAttributes(typeof(InjectableAttribute),
                    true);
                var attribute = attributes[0];
                var implementedInterface = attribute.ImplementedInterface;
                switch (attribute.Scope)
                {
                    case DependencyInjectionScope.Scoped:
                        services.AddScoped(implementedInterface, currentType);
                        break;
                    case DependencyInjectionScope.PerDependency:
                        services.AddTransient(implementedInterface, currentType);
                        break;
                    case DependencyInjectionScope.Singleton:
                        services.AddSingleton(implementedInterface, currentType);
                        break;
                }
            }
        }
    }
    
}

Now to use this, here is an example of a service class:现在要使用它,这里有一个服务 class 的例子:

[Injectable(typeof(ICustomerInfoService), DependencyInjectionScope.Scoped)]
public class CustomerInfoService : ICustomerInfoService
{

}

And to register eveything in my ConfigureServices method:并在我的 ConfigureServices 方法中注册所有内容:

services.RegisterDependencies(typeof(Startup).Assembly);

Hope this helps:D希望这有帮助:D

An overload extension already exists for AddScoped that takes the service and implementation type.采用服务和实现类型的AddScoped已经存在重载扩展。

/// Adds a scoped service of the type specified in <paramref name="serviceType"/> with an
/// implementation of the type specified in <paramref name="implementationType"/> to the
/// specified <see cref="IServiceCollection"/>.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection"/> to add the service to.</param>
/// <param name="serviceType">The type of the service to register.</param>
/// <param name="implementationType">The implementation type of the service.</param>
/// <returns>A reference to this instance after the operation has completed.</returns>
/// <seealso cref="ServiceLifetime.Scoped"/>
public static IServiceCollection AddScoped(
    this IServiceCollection services,
    Type serviceType,
    [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType)
{
    ThrowHelper.ThrowIfNull(services);
    ThrowHelper.ThrowIfNull(serviceType);
    ThrowHelper.ThrowIfNull(implementationType);

    return Add(services, serviceType, implementationType, ServiceLifetime.Scoped);
}

Source 来源

Which when applied to your example would look like当应用于您的示例时,它看起来像

//...

foreach (var processor in processors) {
    serviceCollection.AddScoped(processor);

    serviceCollection.AddScoped(processorInterface, processor);
}

//...

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

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