.net core 依赖注入

才开始学习.net core 很多东西只能是一点点摸索,一点点积累吧

 为什么要用依赖注入就不说了,应该都理解

下面开始介绍在.net core 中怎么用

 在.net core 中微软已经把依赖注入的一些东西系我们封装好了,拿来用就可以了还是很方面的

 

首先我们在项目中 定义一个接口层和一个接口实现层

然后在Startup类中 加入

services.AddTransient<Itest, test>();

然后在控制器构造函数中 这么定义

private readonly Itest _test;

public HomeController(Itest _test) {
this._test = _test;

}

这样实例就被初始化了

如果一个接口对应多个实现框架会把所有实例都会给返回来可以这样定义

private readonly IEnumerable<Itest> _test;

public HomeController(IEnumerable<Itest> _test) {
this._test = _test;

}
public IActionResult Index()
{
foreach (var sv in _test)
{
string name = sv.getName();
}
return View();
}

但是现在我们每新增一个实现接口的类都需要再Startup类中注入一个,如果一个项目有很多,这样会很难维护,所以我们用到了反射

 

   /// <summary>  
        /// 获取程序集中的实现类对应的多个接口
        /// </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[]>();
        }
      //集中注册服务
            foreach (var item in GetClassName("Service"))
            {
                foreach (var typeArray in item.Value)
                {
                    services.AddScoped(typeArray, item.Key);
                }
            }

完整代码如下:

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支持

            //集中注册服务
            foreach (var item in GetClassName("Service"))
            {
                foreach (var typeArray in item.Value)
                {
                    services.AddScoped(typeArray, item.Key);
                }
            }
            services.AddUnitOfWork<ProductContext>();//添加UnitOfWork支持
                                                     //services.AddScoped(typeof(IProductService), typeof(ProductService));//用ASP.NET Core自带依赖注入(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>  
        /// 获取程序集中的实现类对应的多个接口
        /// </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[]>();
        }
    }
}

补充一个知识点

services
这里有三种Add方法,分别代表不同的生命周期:

  • AddSingleton:单个实例,生命周期最长,无限长。

  • AddTransient:随用随销毁,生命周期最短。

  • AddScoped:生命周期在客户端与服务器的单次会话中,只要会话不结束,就不会被销毁。



 

posted @ 2019-05-13 11:27  墨笔淡红尘  阅读(409)  评论(0编辑  收藏  举报