• autofac实现批量注入


     省略接口和类的实现,具体如上图:

    using Autofac;
    using System;
    using System.Linq;
    using System.Reflection;
    namespace autofacBatchResolver
    {
    class Program
    {
    static void Main(string[] args)
    {
    var builder = DependencyResolver();
    using (var container = builder.Build())
    {
    IFunciton1 fun = container.Resolve<IFunciton1>();
    IService service = container.Resolve<IService>();
    Console.WriteLine(service.GetUsers());
    Console.WriteLine(fun.GetName());
    }
    Console.ReadLine();
    }
    static ContainerBuilder DependencyResolver()
    {
    var builder = new ContainerBuilder();
    Type basetype = typeof(IDependency); //获取顶级接口类型
    builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
    .Where(t => basetype.IsAssignableFrom(t) && t.IsClass) //查询继承自顶级接口IDependency的实现类,如果没有这句,则注册所有当前运行环境中接口实现类
    .AsImplementedInterfaces().InstancePerLifetimeScope();
    return builder;

    }
    }
    }

  • 相关阅读:
    常用命令
    linux是文件里的内容整齐
    centos 7新机使用前操作
    Symmetric Tree @leetcode
    Binary Tree Inorder Traversal @leetcode
    [转]快速排序
    Remove Duplicates from Sorted Array @leetcode
    Remove Element @leetcode
    随笔1
    Unique Binary Search Trees @leetcode
  • 原文地址:https://www.cnblogs.com/sundh1981/p/13925650.html
Copyright © 2020-2023  润新知