3.依赖注入Castle Windsor

一、概述

ABP使用Castle Windsor框架进行依赖注入(构造器注入和属性注入)。ABP会自动将Repositories,Domain Services,Application Services MVC控制器,Web API控制器进行注册

二、使用

2.1自动注册

我们无需进行任何操作,ABP自动会进行注册。要做的只是

  • 将程序集注册到容器中(IocManager.RegisterAssemblyByConvention(Assembly.GetExecutingAssembly());)
  • 按约定实现接口:IApplicationService,IRepository即可

2.2自定义注册

2.2.1 实现ISingletonDependency接口

实现ISingletonDependency接口ABP将会自动注册该类

    public class MyModuleConfig:ISingletonDependency
    {
        public bool SampleConfig1  { get; set; }
        public string SampleConfig2 { get; set; }
    }

2.2.2 使用IocManager注册

  public override void PreInitialize()
  {
       IocManager.Register();
  }

2.2.3 使用Castle Windsor 注册

  public override void PreInitialize()
  {
       IocManager.IocContainer.Register(Classes.FromThisAssembly().BasedOn());
  }

2.2.4实现IWindsorInstaller接口

 public class MyInstaller : IWindsorInstaller
    {
        public void Install(IWindsorContainer container, IConfigurationStore store)
        {
            container.Register(Classes.FromThisAssembly().BasedOn());
        }
    }

三、其他

3.1 可以构造注入IIocManager,然后手动解析

        private readonly IIocManager _iocManager;
        public TasksController(IIocManager iocManager)
        {
            _iocManager = iocManager;
        }

        public ActionResult Index()
        {
            using(var scope= _iocManager.CreateScope())
            {
                var simple = scope.Resolve();
                if (simple.SampleConfig2 == "abc")
                {
                    return View(new List { });
                }
            }

你可能感兴趣的:(3.依赖注入Castle Windsor)