Use ASP.netCore's own DI (DependencyInjection) to achieve batch dependency injection

ASP.net Core comes with DI (dependency injection), which is used as follows:

services.AddScoped(typeof(IProductService), typeof(ProductService));

If there are many services, it will definitely cause the files to be difficult to maintain

So you need to use reflection batch to achieve registration

The core code is as follows:

A class may indirectly inherit multiple interfaces (for example: public and internal interfaces), here we use the implementation class as the Key and the inherited interface as the value to construct a collection

copy code
     /// <summary>  
        /// Get multiple interfaces corresponding to the implementation class in the assembly
        /// </summary>  
        /// <param name="assemblyName">程序集</param>
        public Dictionary<Type, Type[]> GetClassName(string assemblyName)
        {
            if (!String.IsNullOrEmpty(assemblyName))
            {
                Assembly assembly = Assembly.Load(assemblyName);
                List<Type> ts = assembly.GetTypes().ToList();

                var result = new Dictionary<Type, Type[]>();
                foreach (var item in ts.Where(s => !s.IsInterface))
                {
                    var interfaceType = item.GetInterfaces();
                    result.Add(item, interfaceType);
                }
                return result;
            }
            return new Dictionary<Type, Type[]>();
        }
copy code

register:

We can now put concrete registrations such as

services.AddScoped(typeof(IProductService), typeof(ProductService));

Change it to:

copy code
        //Centralized registration service
            foreach (var item in GetClassName("Service"))
            {
                foreach (var typeArray in item.Value)
                {
                    services.AddScoped(typeArray, item.Key);
                }
            }
copy code

 Full code:

copy code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.EntityFrameworkCore;
using Entity.Table;
using DAL;
using System.Reflection;
using Service;

namespace ASP.NetCoreAPI
{
    public class Startup
    {
        public Startup (IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ProductContext>(options =>
                options.UseMySql(Configuration.GetConnectionString("MySqlConnection")));//添加Mysql支持

            //Centralized registration service
            foreach (var item in GetClassName("Service"))
            {
                foreach (var typeArray in item.Value)
                {
                    services.AddScoped(typeArray, item.Key);
                }
            }
            services.AddUnitOfWork<ProductContext>();//Add UnitOfWork support
                                                     //services.AddScoped(typeof(IProductService), typeof(ProductService));//Inject the classes used with ASP.NET Core's own dependency injection (DI)
            services.AddMvc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc();
        }

        /// <summary>  
        /// Get multiple interfaces corresponding to the implementation class in the assembly
        /// </summary>  
        /// <param name="assemblyName">程序集</param>
        public Dictionary<Type, Type[]> GetClassName(string assemblyName)
        {
            if (!String.IsNullOrEmpty(assemblyName))
            {
                Assembly assembly = Assembly.Load(assemblyName);
                List<Type> ts = assembly.GetTypes().ToList();

                var result = new Dictionary<Type, Type[]>();
                foreach (var item in ts.Where(s => !s.IsInterface))
                {
                    var interfaceType = item.GetInterfaces();
                    result.Add(item, interfaceType);
                }
                return result;
            }
            return new Dictionary<Type, Type[]>();
        }
    }
}
copy code
Reprinted from http://www.cnblogs.com/xiaoliangge/p/7642372.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325124998&siteId=291194637