Castle Windsor 注册组件

1、逐个注册组件
即对每个接口通过代码指定其实现类,代码:

container.Register(
    Component.For<IMyService>() //接口
    .ImplementedBy<MyService>() //实现类
);

典型应用场景:例如定义了一个日志记录接口,放到一个独立程序集中。具体实现可能有多种方式(日志以文本文件/XML文件/数据库等不同方式存储),则可以为每个实现类建立一个独立的程序集,在各程序集中将自身注册为接口的实现。这样当我们需要日志的某个存储形式时,选择对应的dll即可

2、按规则批量注册
和1比较类似,不同的是,不用逐个指定接口和实现类,而是指定一个规则,Windsor会用规则去匹配和注册当前应用中所有程序集。代码:

container.Register(Classes.FromThisAssembly()    //当前程序集,也可以调用其它方法,如FromAssemblyInDirectory()等
                    .InSameNamespaceAs<RootComponent>() //与RootComponent类具有相同的命名空间,还可以用InNamespace("Com.Spbdev")直接指定命名空间
                    .WithService.DefaultInterfaces()    
                    .LifestyleTransient());    //生命周期

3、按程序集安装注册
与按照规则批量注册类似,差别在于每个程序集内部自己实现一个IWindsorInstaller接口来定义注册规则。也就是将注册规则下放到程序集。
首先,需要指定对哪些程序集进行安装注册(只指定对程序集的搜索规则):
container.Install(FromAssembly.InDirectory(new AssemblyFilter("Extensions")));//Extensions目录下的所有程序集。


其次,每个程序集内通过一个或多个实现了IWindsorInstaller接口的类,来定义哪些Interface和实现类要注册到容器。
如下代码是官网上的一个范例:

public class RepositoriesInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.Register(Classes.FromThisAssembly()
                            .Where(Component.IsInSameNamespaceAs<RepositoriesInstaller>())
                            .WithService.DefaultInterfaces()
                            .LifestyleTransient());
    }
}

意思是当前程序集中,与RepositoriesInstaller具有相同命名空间的接口、实现,都注册到IOC容器中。

4、XML配置文件注册
用构造函数方式注册:

IWindsorContainer container = new WindsorContainer("dependencies.config");

或通过Install方法

container.Install(
    Configuration.FromXmlFile("dependencies.config"));

配置文件格式如下

复制代码
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <installers>
    <install type="WindsorInstaller.CustomerInstaller,WindsorInstaller"/>
    <install type="WindsorInstaller.SecondInstaller,WindsorInstaller"/>
  </installers>
</configuration>
复制代码

Windsor自动获取xml文件中的installers

也可以写在应用程序配置文件中

复制代码
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="castle" type="Castle.Windsor.Configuration.AppDomain.CastleSectionHandler, Castle.Windsor" />
  </configSections>
  <castle>
    <installers>
      <install type="WindsorInstaller.CustomerInstaller,WindsorInstaller"/>
      <install type="WindsorInstaller.SecondInstaller,WindsorInstaller"/>

      <!--查找该程序集下所有IWindsorInstaller接口的类型进行注册-->
      <!--<install assembly="WindsorInstaller"></install>-->

      <!--查找dll文件-->
      <!--<install directory="Extensions" fileMask="*.dll"></install>-->
    </installers>
  </castle>
</configuration>
复制代码
原文地址:https://www.cnblogs.com/chenyishi/p/9341723.html