【问题标题】:How to automatically add service in DI如何在 DI 中自动添加服务
【发布时间】:2020-04-29 07:40:29
【问题描述】:

我正在开发一个 ASP Net Core Web API。我使用 DDD 架构。 我的控制器有一个层,我的服务有一个层。我不为我的服务使用接口,因为它是我的业务代码。所以,它不会有另一个实现。 在我的控制器中,我想使用 DI 来注入服务。

我所有的代码都在类库中,在我的 Api 主机旁边。 所有服务都继承BaseServiceBaseService<TEntity, TRepository>

我已经创建了工具,其中一个包含一个 DiHelper lile:

    /// <summary>
    /// Helper for the dependency injection
    /// </summary>
    public static class DiHelper
    {
        /// <summary>
        /// Add all services in the DI
        /// </summary>
        /// <param name="serviceCollection">Service collection</param>
        /// <param name="assemblies">Assemblies to browse</param>
        /// <param name="baseServiceTypes">Base types which are inherited or implemented by services</param>
        public static void AddAllServices(this IServiceCollection serviceCollection,
            IEnumerable<Assembly> assemblies,
            IEnumerable<Type> baseServiceTypes)
        {
            //Get all types
            assemblies
                .SelectMany(x => x.GetTypes()) //Get all types
                .Where(type =>
                    !(type.IsAbstract || type.IsInterface) //Get not abstract class
                    && (type
                            .GetAllBaseTypes()
                            .Any(baseType => baseServiceTypes.Any(x => x.GUID == baseType.GUID))
                        ||
                        type
                            .GetInterfaces()
                            .Any(baseInterface => baseServiceTypes.Any(x => x.GUID == baseInterface.GUID))))
                .ToList()
                .ForEach(x => serviceCollection.AddScoped(x)); //Add services to DI
        }
    }

此代码在程序集中搜索从列表继承的所有类型。

我从 Startup 这样称呼他:

        /// <summary>
        /// Add the services to the DI
        /// </summary>
        /// <param name="services"></param>
        private static void AddBusinessServices(IServiceCollection services)
        {
            //Add all services
            services.AddAllServices(
                assemblies: Assembly
                    .GetExecutingAssembly()
                    .GetReferencedAssemblies()
                    .Select(Assembly.Load)
                    .ToList(),
                baseServiceTypes: new List<Type>() {typeof(BaseService), typeof(BaseService<,>)});
        }

我在我的 Api 中引用了我的所有项目 => 演示项目包含控制器

我不知道为什么,但是当我运行代码时,没有找到所有的演示项目,因此,由于没有添加服务,因此 DI 不起作用。

要重现它,您可以下载github repo中的项目 我的工具发布在 nuget 上,但你可以在那里看到 here, on the github repo

谢谢!

【问题讨论】:

    标签: c# asp.net-core .net-core


    【解决方案1】:

    为此,我会尝试使用已经存在的、经过现场测试的库。

    Scrutor 是我比较熟悉的替代方案之一。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-04-07
      • 1970-01-01
      • 1970-01-01
      • 2014-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多