AutoFac自动注入的实现过程

今天去面试,面试官问了AutoFac怎么实现自动过程的,一下把我问蒙了,平时只会把代码搬过来用,没有深入研究,这次经历也算是一个教训吧。回来之后把实现过程研究了一下,写个笔记记录一下。

一、依赖注入接口

先简介介绍一下依赖注入的接口

1、声明了一个标记接口,标明所有继承自此接口的

    /// <summary>
    /// 依赖注入接口,表示该接口的实现类将自动注册到IoC容器中
    /// </summary>
    public interface IDependency
    {
    }

2、声明了一个基础接口,封装通用的增删改查方法

    public interface IBaseContract<T> : IDependency
	{
        IQueryable<T> Entities { get; }
        //OperationResult 是自己封装的一个操作结果,不用在意
        OperationResult Insert(params T[] entities);
        OperationResult Update(params T[] entities);
        T View(int Id);
	}

3、声明具体的实体类接口,接口中可以封装一些自己独有的方法

 public interface IStudentContract : IBaseContract<Student>
 {
      string GetName();
 }

4、使用
在控制器的构造函数中使用

 public class HomeController : Controller
    {
        private IStudentContract _student;

        public HomeController(IStudentContract student)
        {
            _student = student;
        }

        public ActionResult Index()
        {
            return Content(_student.GetName());
        }
    }
二、自动注入过程
protected void AutofacRegister()
        {
            var builder = new ContainerBuilder();
            /* 1、注册
             * RegisterGeneric:注册非参数化泛型类型:RegisterGeneric(typeof(类)).As(typeof(接口))
             * RegisterType:通过RegisterType<类>.As<接口>() 来注册不是泛型的类
             */
            builder.RegisterGeneric(typeof(Repository<,>)).As(typeof(IRepository<,>));
            

            /* 2、获取接口类型
             * 通过IDependency标记需要依赖注入的接口
             * 注册所有实现了IDependency接口的类型
             */
            Type baseType = typeof(IDependency);


            /* 3、获取所有程序集
             * 当CLR COM服务器初始化时,它会创建一个AppDomain。 AppDomain是一组程序集的逻辑容器
             */
            //var assemblies = AppDomain.CurrentDomain.GetAssemblies();//这种写法AppDomain重新启动后会丢失程序集
            var assemblies = System.Web.Compilation.BuildManager.GetReferencedAssemblies().Cast<Assembly>().ToArray();
   
            /* 4、自动注册接口
             * 筛选出对应条件的接口
             * IsAssignableFrom:返回true的条件:是否直接或间接实现了IDependency
             * IsAbstract:是否为抽象类
             * AsImplementedInterfaces:以接口的形式注册
             * InstancePerLifetimeScope:同一个Lifetime生成的对象是同一个实例
             */
            builder.RegisterAssemblyTypes(assemblies)
                .Where(type => baseType.IsAssignableFrom(type) && !type.IsAbstract)               .AsImplementedInterfaces().InstancePerLifetimeScope();

            /*5、自动注册MVC与api控制器
             */
            builder.RegisterControllers(Assembly.GetExecutingAssembly()); 
                    builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

		   IContainer container = builder.Build();

            /*6、ApiController WebApi注入
             */
            var webapiresolver = new AutofacWebApiDependencyResolver(container); 
            GlobalConfiguration.Configuration.DependencyResolver = webapiresolver;

            /*7、mvc注入
            */
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }

在 Application_Start 方法调用 AutofacRegister()

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
在使用 Autofac 进行批量依赖注入时,可以使用 Autofac 的 `RegisterAssemblyTypes` 方法实现。 首先,需要在程序集中标记需要注入的类型,可以使用 `Autofac.Module` 类进行实现。例如: ```csharp using Autofac; public class MyModule : Autofac.Module { protected override void Load(ContainerBuilder builder) { builder.RegisterType<MyService>().As<IMyService>(); builder.RegisterType<MyRepository>().As<IMyRepository>(); // 注册其他需要注入的类型 } } ``` 然后,在 `Global.asax.cs` 文件中,使用 `ContainerBuilder` 类创建容器,并把需要注入的模块注册进去。例如: ```csharp using Autofac; using Autofac.Integration.WebApi; using System.Reflection; using System.Web.Http; public class WebApiApplication : System.Web.HttpApplication { protected void Application_Start() { var builder = new ContainerBuilder(); builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); builder.RegisterAssemblyModules(Assembly.GetExecutingAssembly()); var container = builder.Build(); GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container); } } ``` 这样,就可以实现批量依赖注入了。在需要使用注入的类型时,可以通过构造函数注入或属性注入的方式获取实例。例如: ```csharp public class MyController : ApiController { private readonly IMyService _myService; public MyController(IMyService myService) { _myService = myService; } [HttpGet] public IHttpActionResult MyAction() { // 使用 MyService return Ok(); } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值