如何在DI

时间:2020-04-29 07:40:29

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

我正在研究ASP Net Core Web API。我使用DDD架构。 我的控制器有一层,服务有一层。我不为我的服务使用接口,因为这是我的业务代码。因此,它将没有其他实现。 在我的控制器中,我想使用DI来注入服务。

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

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

    /// <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中引用了我所有的项目=>演示项目包含控制器

Image of my projects

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

要复制它,可以在github repo中下载项目 我的工具发布在nuget上,但您可以在here, on the github repo

上看到

谢谢!

1 个答案:

答案 0 :(得分:0)

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

Scrutor 是我比较熟悉的选择之一。