Net Core 自动注册实现类到IOC

1、新建一个类库项目HJ.Services 新建一个父类接口IServiceSupport其他接口继承他,新建一个接口类并新建一个实现类

     
    /// 
    ///  父类接口  主要是用于依赖注入判断使用
    /// 
    public interface IServiceSupport
    {
    }
    /// 
    /// 继承IServiceSupport接口
    /// 
    public interface IUserService: IServiceSupport
    {
        int GetUserCount();
    }
    /// 
    /// 实现接口类
    /// 
    public class UserService : IUserService
    {
        public int GetUserCount()
        {
            return 666;
        }
    }

2、新建Net Core MVC测试项目并引用HJ.Services类库

     
    配置Startup.cs文件的方法ConfigureServices
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc(); //加载HJ.Services程序集 Assembly asm = Assembly.Load(new AssemblyName("HJ.Services")); //获取实现IServiceSupport接口并不是抽象类的类 var serviceTypes = asm.GetTypes().Where(t => typeof(IServiceSupport).IsAssignableFrom(t) && !t.GetTypeInfo().IsAbstract); foreach (var serviceType in serviceTypes) { //serviceType为接口实现类 foreach (var intfType in serviceType.GetInterfaces()) { //intfType实现类的接口类 services.AddSingleton(intfType, serviceType); } } }

3、在使用的类中进行构造函数注入

    
///
        /// 在使用类中进行构造函数注入
        ///
        private IAdminUserService AdminUserSvc;
        private IUserService userSvc;

        private IHostingEnvironment hostingEnv;
        ///
        /// 现在Net Core 只支持构造函数注入
        ///
        ///
        ///
        ///
        public HomeController(IAdminUserService AdminUserSvc,
            IUserService userSvc, IHostingEnvironment hostingEnv)
        {
            this.AdminUserSvc = AdminUserSvc;
            this.userSvc = userSvc;
            this.hostingEnv = hostingEnv;
        }

4、在使用类中就可以调用注入类的方法

     
  public IActionResult Index()
        {
            return Content("a" + AdminUserSvc.GetPassword("aa") + " ,"
                + userSvc.GetUserCount());
        }
posted @ 2018-05-06 21:55  野村小孩  阅读(67)  评论(0)    收藏  举报