Castle Windsor of dependency injection container

1. Use of Windsor

Windsor, as a kind of dependency injection container, is more convenient to use. We directly add Castle Windsor to Nuget, and Castle.Core  and  Castle.Windsor will be automatically introduced, which can be used normally.

1. Register component by component

Use the Component in the registered module

 IWindsorContainer container = new WindsorContainer();
            container.Register(Component.For<IAppleService>() //接口
    .ImplementedBy<AppleService>()); 

 Taking a special example here, we register an instance with parameters, and we directly use Resolve to realize the injection of cash

    public class AppleService : IAppleService
    {
        public AppleService(decimal price)
        {
            this.Price = price;
        }
        public decimal Price { get; set ; }
        public void Output()
        {
            Console.WriteLine(Price);
        }
    }
// The specific implementation is injected into 
 var apple= container.Resolve<IAppleService>( new Dictionary< string , decimal >() { { " price " , 222.22m } });
            apple.Output();
            Console.ReadLine();

An IDictionary parameter is provided in the Resolve method, so we can pass the parameter in through Dictionary or HashTable.

It is possible to register a single component when there are few classes in our project, but in actual projects, we often follow a single responsibility and create a large number of files. Using the above method will become a disaster.

2. Batch registration through rules (register through class library)

  container.Register(Classes.FromThisAssembly()    // The current assembly, you can also use FromAssemblyInDirectory(), etc. 
                    InSameNamespaceAs<CatService>() // Has the same namespace as the CatService class
                    // .InNamespace("Windsor") // Specify the namespace 
                     directly.WithService.DefaultInterfaces()
                     .LifestyleTransient());    //临时生命周期
            var apple= container.Resolve<IAppleService>(new Dictionary<string,decimal>() { { "price",222.22m} });
            var cat = container.Resolve<ICatService>();
            cat.Eat();
            apple.Output();

 The detailed API can be used by the detailed description model in BasedOnDescriptor

3. Enter the new registration through the installer Installer

Because the test code is tested using the console program, in the above two methods, we directly write the registered code in the Main method, which is highly coupled and inconvenient to manage. So you can use the installer to register

(1) Implement the installer through the interface IWindsorInstaller

// Define 
 public  class ServiceInstaller : IWindsorInstaller
    {
        public void Install(IWindsorContainer container, IConfigurationStore store)
        {
            container.Register(Classes.FromThisAssembly()    // The current assembly, you can also use FromAssemblyInDirectory(), etc. 
                   InSameNamespaceAs<CatService>() // Has the same namespace as the 
                   CatService class.WithServiceDefaultInterfaces() // Register all default Interface and implementation 
                    class.LifestyleTransient());     // Temporary life cycle 
        }
    }

// Registration
     // 3. Register through the installer 
            container.Install(FromAssembly.Named( " Windsor " ));
             var apple= container.Resolve<IAppleService>( new Dictionary< string , decimal >() { { " price " , 222.22m } });
             var cat = container.Resolve<ICatService> ();
            cat.Eat();
            apple.Output();

 

When registering through the installer above, the installer under the specified assembly Windor will be called, so there is a problem at this time, if my installer is defined under the folder of the current class library, can it be registered and used? ?

It is found through testing that it can be registered.

Another question, if the classes registered in our installer are duplicated, will there be duplicate registrations in our container?

It is found through testing that it will not be repeatedly registered.

still have a question

Will it report an error?

The answer is no. This can be found in the source code of CastleWindsor. This is determined by its implementation mechanism. It will judge repetition and maintain this Dictionary.

(2) Through the xml configuration file

// Use the configuration file container.Install(Configuration.FromXmlFile("WindsorSetting.xml")); 
            var cat = container.Resolve<ICatService> ();
            cat.Eat();
            Console.ReadLine();
// Define configuration file WindsorSetting.xml 
<?xml version= " 1.0 " encoding= " utf-8 " ?>
<configuration>
  <installers>
    <install type="Windsor.ServiceInstaller,Windsor"/>
   
  </installers>
  <!--<components>
    <component type="Windsor.CatService,Windsor" service="Windsor.ICatService,Windsor">
      
    </component>
  </components>-->
</configuration>

 

 The string in type, the first one represents the specific installer class under the namespace, and the second one represents the assembly name

In the above code, we customized the xml file, of course, we can directly use the app.config in the project

//调用 
container.Install(Configuration.FromAppConfig());
            var cat = container.Resolve<ICatService>();
            cat.Eat();
//配置
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="castle" type="Castle.Windsor.Configuration.AppDomain.CastleSectionHandler, Castle.Windsor" />
  </configSections>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
    </startup>

  <castle>
    <installers>
      <install type="Windsor.ServiceInstaller,Windsor"/>
      <!--Find the types of all IWindsorInstaller interfaces under the assembly to register -->
      <!--<install assembly="WindsorInstaller"></install>-->

      <!--Find dll file-->
      <!--<install directory="Extensions" fileMask="*.dll"></install>-->
    </installers>
  </castle>
</configuration>

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325261980&siteId=291194637