SlideShare une entreprise Scribd logo
1  sur  30
Télécharger pour lire hors ligne
AMIR BARYLKO

                    ADVANCED IOC
                      WINDSOR
                       CASTLE

                              DOT NET UG
                               NOV 2011

Amir Barylko - Advanced IoC                MavenThought Inc.
FIRST STEPS
                                Why IoC containers
                              Registering Components
                                      LifeStyles
                                       Naming



Amir Barylko - Advanced IoC                            MavenThought Inc.
WHY USE IOC

  • Manage           creation and disposing objects
  • Avoid        hardcoding dependencies
  • Dependency                injection
  • Dynamically               configure instances
  • Additional            features
Amir Barylko - Advanced IoC                           MavenThought Inc.
REGISTRATION

  • In   order to resolve instances, we need to register them
  Container.Register(
         // Movie class registered
         Component.For<Movie>(),


         // IMovie implementation registered
         Component.For<IMovie>().ImplementedBy<Movie>()
  );


Amir Barylko - Advanced IoC                           MavenThought Inc.
GENERICS

  •What If I want to register a generic class?
  container.Register(

         Component

                .For(typeof(IRepository<>)

                .ImplementedBy(typeof(NHRepository<>)

  );




Amir Barylko - Advanced IoC                             MavenThought Inc.
DEPENDENCIES
        Component
          .For<IMovieFactory>()
          .ImplementedBy<NHMovieFactory>(),

        Component
          .For<IMovieRepository>()
          .ImplementedBy<SimpleMovieRepository>()


  public class SimpleMovieRepository : IMovieRepository
  {
      public SimpleMovieRepository(IMovieFactory factory)
      {
          _factory = factory;
      }
  }

Amir Barylko - Advanced IoC                            MavenThought Inc.
LIFESTYLE

  • Singleton      vs Transient

  • Which       one is the default? And for other IoC tools?

  container.Register(
     Component.For<IMovie>()
        .ImplementedBy<Movie>()
        .LifeStyle.Transient
     );


Amir Barylko - Advanced IoC                                    MavenThought Inc.
RELEASING

  • Do     I need to release the instances?




Amir Barylko - Advanced IoC                   MavenThought Inc.
NAMING

  • Who’s       the one resolved?
  container.Register(
         Component
            .For<IMovie>()
            .ImplementedBy<Movie>(),
         Component
            .For<IMovie>()
            .ImplementedBy<RottenTomatoesMovie>()
  );


Amir Barylko - Advanced IoC                         MavenThought Inc.
NAMING II

  • Assign     unique names to registration
  container.Register(
      ...

         Component
             .For<IMovie>()
             .ImplementedBy<RottenTomatoesMovie>()
             .Named("RT")
  );

  container.Resolve<IMovie>("RT");



Amir Barylko - Advanced IoC                          MavenThought Inc.
JOGGING
                                   Installers
                              Using Conventions
                                 Depend On




Amir Barylko - Advanced IoC                       MavenThought Inc.
INSTALLERS

  • Where        do we put the registration code?

  • Encapsulation

  • Partition      logic

  • Easy    to maintain




Amir Barylko - Advanced IoC                         MavenThought Inc.
INSTALLER EXAMPLE
  container.Install(
   new EntitiesInstaller(),
   new RepositoriesInstaller(),

   // or use FromAssembly!
   FromAssembly.This(),
   FromAssembly.Named("MavenThought...."),
   FromAssembly.Containing<ServicesInstaller>(),
   FromAssembly.InDirectory(new AssemblyFilter("...")),
   FromAssembly.Instance(this.GetPluginAssembly())
  );



Amir Barylko - Advanced IoC                   MavenThought Inc.
XML CONFIG
      var res = new AssemblyResource("assembly://.../
      ioc.xml")

  container.Install(
     Configuration.FromAppConfig(),
     Configuration.FromXmlFile("ioc.xml"),
     Configuration.FromXml(res)
     );




Amir Barylko - Advanced IoC                         MavenThought Inc.
CONVENTIONS
  Classes

       .FromAssemblyContaining<IMovie>()

       .BasedOn<IMovie>()

       .WithService.Base() // Register the service

       .LifestyleTransient() // Transient lifestyle




Amir Barylko - Advanced IoC                           MavenThought Inc.
CONFIGURE COMPONENTS
  Classes

     .FromAssemblyContaining<IMovie>()

     .BasedOn<IMovie>()

      .LifestyleTransient()

     // Using naming to identify instances

     .Configure(r => r.Named(r.Implementation.Name))




Amir Barylko - Advanced IoC                        MavenThought Inc.
DEPENDS ON
  var rtKey = @"the key goes here";
  container.Register(
     Component
      .For<IMovieFactory>()
      .ImplementedBy<RottenTomatoesFactory>()
     .DependsOn(Property.ForKey("apiKey").Eq(rtKey))
  );

  .DependsOn(new { apiKey = rtKey } ) // using anonymous class

  .DependsOn(
    new Dictionary<string,string>{
      {"APIKey", twitterApiKey}}) // using dictionary




Amir Barylko - Advanced IoC                               MavenThought Inc.
SERVICE OVERRIDE
  container.Register(
    Component
        .For<IMovieFactory>()
        .ImplementedBy<IMDBMovieFactory>()
        .Named(“imdbFactory”)

    Component
       .For<IMovieRepository>()
       .ImplementedBy<SimpleMovieRepository>()
       .DependsOn(Dependency.OnComponent("factory", "imdbFactory"))
  );




Amir Barylko - Advanced IoC                               MavenThought Inc.
RUN FOREST! RUN!
                                   Startable Facility
                              Interface Based Factories
                                     Castle AOP




Amir Barylko - Advanced IoC                               MavenThought Inc.
STARTABLE FACILITY

  • Allows      objects to be started when they are created

  • And     stopped when they are released

  • Start and stop methods have to be public, void and no
     parameters

  • You  can use it with POCO objects specifying which method
     to use to start and stop


Amir Barylko - Advanced IoC                              MavenThought Inc.
STARTABLE CLASS
  public interface IStartable
  {
      void Start();
      void Stop();
  }

  var container = new WindsorContainer()
      .AddFacility<StartableFacility>()
      .Register(
          Component
             .For<IThing>()
             .ImplementedBy<StartableThing>()
      );


Amir Barylko - Advanced IoC                     MavenThought Inc.
FACTORIES

  • Common          pattern to create objects

  • But    the IoC is some kind of factory too...

  • Each     factory should use the IoC then....

  • Unless      we use Windsor!!!!




Amir Barylko - Advanced IoC                         MavenThought Inc.
TYPED FACTORIES

  • Create      a factory based on an interface

  • Methods        that return values are Resolve methods

  • Methods        that are void are Release methods

  • Collection            methods resolve to multiple components




Amir Barylko - Advanced IoC                                  MavenThought Inc.
REGISTER FACTORY
  Kernel.AddFacility<TypedFactoryFacility>();

  Register(
      Component
         .For<IMovie>()
         .ImplementedBy<NHMovie>()
         .LifeStyle.Transient,

         Component.For<IMovieFactory>().AsFactory()
  );




Amir Barylko - Advanced IoC                           MavenThought Inc.
CASTLE AOP

  • Inject    code around methods

  • Cross     cutting concerns

  • Avoid      mixing modelling and usage

  • Avoid      littering the code with new requirements




Amir Barylko - Advanced IoC                               MavenThought Inc.
INTERCEPTORS
  Register(
      Component
          .For<LoggingInterceptor>()
          .LifeStyle.Transient,
      Component
          .For<IMovie>()
          .ImplementedBy<NHMovie>()
          .Interceptors(InterceptorReference
                          .ForType<LoggingInterceptor>()).Anywhere
          .LifeStyle.Transient
  );




Amir Barylko - Advanced IoC                               MavenThought Inc.
LOGGING
  public class LoggingInterceptor : IInterceptor
  {
      public void Intercept(IInvocation invocation)
      {
          Debug.WriteLine("Before execution");
          invocation.Proceed();
          Debug.WriteLine("After execution");
      }
  }




Amir Barylko - Advanced IoC                       MavenThought Inc.
NOTIFY PROPERTY CHANGED
  Register(
      Component
          .For<NotifyPropertyChangedInterceptor>()
          .LifeStyle.Transient,
      Component
          .For<IMovieViewModel>()
          .ImplementedBy<MovieViewModel>()
          .Interceptors(InterceptorReference
                       .ForType<NotifyPropertyChangedInterceptor>())
                       .Anywhere
          .LifeStyle.Transient
      );




Amir Barylko - Advanced IoC                               MavenThought Inc.
QUESTIONS?




Amir Barylko - TDD                MavenThought Inc.
RESOURCES

  • Contact: amir@barylko.com, @abarylko

  • Code      & Slides: http://www.orthocoders.com/presentations

  • Castle     Project Doc: http://docs.castleproject.org




Amir Barylko - Advanced IoC                                 MavenThought Inc.

Contenu connexe

Tendances

Tendances (9)

CDI Integration in OSGi - Emily Jiang
CDI Integration in OSGi - Emily JiangCDI Integration in OSGi - Emily Jiang
CDI Integration in OSGi - Emily Jiang
 
Maximise the Power of OSGi - Carsten Ziegeler & David Bosschaert
Maximise the Power of OSGi - Carsten Ziegeler & David BosschaertMaximise the Power of OSGi - Carsten Ziegeler & David Bosschaert
Maximise the Power of OSGi - Carsten Ziegeler & David Bosschaert
 
081107 Sammy Eclipse Summit2
081107   Sammy   Eclipse Summit2081107   Sammy   Eclipse Summit2
081107 Sammy Eclipse Summit2
 
Vitaliy Makogon: Migration to ivy. Angular component libraries with IVY support.
Vitaliy Makogon: Migration to ivy. Angular component libraries with IVY support.Vitaliy Makogon: Migration to ivy. Angular component libraries with IVY support.
Vitaliy Makogon: Migration to ivy. Angular component libraries with IVY support.
 
Android MvRx Framework 介紹
Android MvRx Framework 介紹Android MvRx Framework 介紹
Android MvRx Framework 介紹
 
OSGi-enabled Java EE applications in GlassFish
OSGi-enabled Java EE applications in GlassFishOSGi-enabled Java EE applications in GlassFish
OSGi-enabled Java EE applications in GlassFish
 
Spring - CDI Interop
Spring - CDI InteropSpring - CDI Interop
Spring - CDI Interop
 
RIBs - Fragments which work
RIBs - Fragments which workRIBs - Fragments which work
RIBs - Fragments which work
 
Javaee6 Overview
Javaee6 OverviewJavaee6 Overview
Javaee6 Overview
 

En vedette (7)

castle-windsor-ioc-demo
castle-windsor-ioc-democastle-windsor-ioc-demo
castle-windsor-ioc-demo
 
Dependency injection& comparative study
Dependency injection& comparative studyDependency injection& comparative study
Dependency injection& comparative study
 
Choosing an IoC container
Choosing an IoC containerChoosing an IoC container
Choosing an IoC container
 
No estimates
No estimatesNo estimates
No estimates
 
User stories deep dive
User stories deep diveUser stories deep dive
User stories deep dive
 
Elm: delightful web development
Elm: delightful web developmentElm: delightful web development
Elm: delightful web development
 
Dot Net Core
Dot Net CoreDot Net Core
Dot Net Core
 

Similaire à ioc-castle-windsor

Rich UI with Knockout.js &amp; Coffeescript
Rich UI with Knockout.js &amp; CoffeescriptRich UI with Knockout.js &amp; Coffeescript
Rich UI with Knockout.js &amp; Coffeescript
Amir Barylko
 
The Basic Concept Of IOC
The Basic Concept Of IOCThe Basic Concept Of IOC
The Basic Concept Of IOC
Carl Lu
 
prdc10-tdd-patterns
prdc10-tdd-patternsprdc10-tdd-patterns
prdc10-tdd-patterns
Amir Barylko
 
Cpl12 continuous integration
Cpl12 continuous integrationCpl12 continuous integration
Cpl12 continuous integration
Amir Barylko
 

Similaire à ioc-castle-windsor (20)

Codemash-advanced-ioc-castle-windsor
Codemash-advanced-ioc-castle-windsorCodemash-advanced-ioc-castle-windsor
Codemash-advanced-ioc-castle-windsor
 
Process Matters (Cloud2Days / Java2Days conference))
Process Matters (Cloud2Days / Java2Days conference))Process Matters (Cloud2Days / Java2Days conference))
Process Matters (Cloud2Days / Java2Days conference))
 
PRDCW-avent-aggregator
PRDCW-avent-aggregatorPRDCW-avent-aggregator
PRDCW-avent-aggregator
 
Introduction to IoC Container
Introduction to IoC ContainerIntroduction to IoC Container
Introduction to IoC Container
 
Pimp Your Pipeline - Central Configuration Management - Jens Saade
Pimp Your Pipeline - Central Configuration Management - Jens SaadePimp Your Pipeline - Central Configuration Management - Jens Saade
Pimp Your Pipeline - Central Configuration Management - Jens Saade
 
Codecamp2015 pimp yourpipeline-saade-jens-1.1
Codecamp2015 pimp yourpipeline-saade-jens-1.1Codecamp2015 pimp yourpipeline-saade-jens-1.1
Codecamp2015 pimp yourpipeline-saade-jens-1.1
 
Rich UI with Knockout.js &amp; Coffeescript
Rich UI with Knockout.js &amp; CoffeescriptRich UI with Knockout.js &amp; Coffeescript
Rich UI with Knockout.js &amp; Coffeescript
 
Micronaut: Changing the Micro Future
Micronaut: Changing the Micro FutureMicronaut: Changing the Micro Future
Micronaut: Changing the Micro Future
 
Spring framework
Spring frameworkSpring framework
Spring framework
 
The Basic Concept Of IOC
The Basic Concept Of IOCThe Basic Concept Of IOC
The Basic Concept Of IOC
 
prdc10-tdd-patterns
prdc10-tdd-patternsprdc10-tdd-patterns
prdc10-tdd-patterns
 
springtraning-7024840-phpapp01.pdf
springtraning-7024840-phpapp01.pdfspringtraning-7024840-phpapp01.pdf
springtraning-7024840-phpapp01.pdf
 
Istio Upgrade Field Guide IstioCon2022.pdf
Istio Upgrade Field Guide IstioCon2022.pdfIstio Upgrade Field Guide IstioCon2022.pdf
Istio Upgrade Field Guide IstioCon2022.pdf
 
Spring framework
Spring frameworkSpring framework
Spring framework
 
Cpl12 continuous integration
Cpl12 continuous integrationCpl12 continuous integration
Cpl12 continuous integration
 
Agile requirements
Agile requirementsAgile requirements
Agile requirements
 
Unit Testing 101
Unit Testing 101Unit Testing 101
Unit Testing 101
 
Docker presentasjon java bin
Docker presentasjon java binDocker presentasjon java bin
Docker presentasjon java bin
 
every-day-automation
every-day-automationevery-day-automation
every-day-automation
 
Continous Delivering a PHP application
Continous Delivering a PHP applicationContinous Delivering a PHP application
Continous Delivering a PHP application
 

Plus de Amir Barylko

Beutiful javascript with coffeescript
Beutiful javascript with coffeescriptBeutiful javascript with coffeescript
Beutiful javascript with coffeescript
Amir Barylko
 
Beutiful javascript with coffeescript
Beutiful javascript with coffeescriptBeutiful javascript with coffeescript
Beutiful javascript with coffeescript
Amir Barylko
 

Plus de Amir Barylko (20)

Functional converter project
Functional converter projectFunctional converter project
Functional converter project
 
Coderetreat hosting training
Coderetreat hosting trainingCoderetreat hosting training
Coderetreat hosting training
 
There's no charge for (functional) awesomeness
There's no charge for (functional) awesomenessThere's no charge for (functional) awesomeness
There's no charge for (functional) awesomeness
 
What's new in c# 6
What's new in c# 6What's new in c# 6
What's new in c# 6
 
Productive teams
Productive teamsProductive teams
Productive teams
 
Who killed object oriented design?
Who killed object oriented design?Who killed object oriented design?
Who killed object oriented design?
 
From coach to owner - What I learned from the other side
From coach to owner - What I learned from the other sideFrom coach to owner - What I learned from the other side
From coach to owner - What I learned from the other side
 
Communication is the Key to Teamwork and productivity
Communication is the Key to Teamwork and productivityCommunication is the Key to Teamwork and productivity
Communication is the Key to Teamwork and productivity
 
Acceptance Test Driven Development
Acceptance Test Driven DevelopmentAcceptance Test Driven Development
Acceptance Test Driven Development
 
Refactoring
RefactoringRefactoring
Refactoring
 
Agile requirements
Agile requirementsAgile requirements
Agile requirements
 
Agile teams and responsibilities
Agile teams and responsibilitiesAgile teams and responsibilities
Agile teams and responsibilities
 
Refactoring
RefactoringRefactoring
Refactoring
 
Beutiful javascript with coffeescript
Beutiful javascript with coffeescriptBeutiful javascript with coffeescript
Beutiful javascript with coffeescript
 
Sass & bootstrap
Sass & bootstrapSass & bootstrap
Sass & bootstrap
 
SDEC12 Beautiful javascript with coffeescript
SDEC12 Beautiful javascript with coffeescriptSDEC12 Beautiful javascript with coffeescript
SDEC12 Beautiful javascript with coffeescript
 
Beutiful javascript with coffeescript
Beutiful javascript with coffeescriptBeutiful javascript with coffeescript
Beutiful javascript with coffeescript
 
PRDC12 advanced design patterns
PRDC12 advanced design patternsPRDC12 advanced design patterns
PRDC12 advanced design patterns
 
Awesome html with ujs, jQuery and coffeescript
Awesome html with ujs, jQuery and coffeescriptAwesome html with ujs, jQuery and coffeescript
Awesome html with ujs, jQuery and coffeescript
 
Nuget
NugetNuget
Nuget
 

Dernier

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Dernier (20)

Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 

ioc-castle-windsor

  • 1. AMIR BARYLKO ADVANCED IOC WINDSOR CASTLE DOT NET UG NOV 2011 Amir Barylko - Advanced IoC MavenThought Inc.
  • 2. FIRST STEPS Why IoC containers Registering Components LifeStyles Naming Amir Barylko - Advanced IoC MavenThought Inc.
  • 3. WHY USE IOC • Manage creation and disposing objects • Avoid hardcoding dependencies • Dependency injection • Dynamically configure instances • Additional features Amir Barylko - Advanced IoC MavenThought Inc.
  • 4. REGISTRATION • In order to resolve instances, we need to register them Container.Register( // Movie class registered Component.For<Movie>(), // IMovie implementation registered Component.For<IMovie>().ImplementedBy<Movie>() ); Amir Barylko - Advanced IoC MavenThought Inc.
  • 5. GENERICS •What If I want to register a generic class? container.Register( Component .For(typeof(IRepository<>) .ImplementedBy(typeof(NHRepository<>) ); Amir Barylko - Advanced IoC MavenThought Inc.
  • 6. DEPENDENCIES Component .For<IMovieFactory>() .ImplementedBy<NHMovieFactory>(), Component .For<IMovieRepository>() .ImplementedBy<SimpleMovieRepository>() public class SimpleMovieRepository : IMovieRepository { public SimpleMovieRepository(IMovieFactory factory) { _factory = factory; } } Amir Barylko - Advanced IoC MavenThought Inc.
  • 7. LIFESTYLE • Singleton vs Transient • Which one is the default? And for other IoC tools? container.Register( Component.For<IMovie>() .ImplementedBy<Movie>() .LifeStyle.Transient ); Amir Barylko - Advanced IoC MavenThought Inc.
  • 8. RELEASING • Do I need to release the instances? Amir Barylko - Advanced IoC MavenThought Inc.
  • 9. NAMING • Who’s the one resolved? container.Register( Component .For<IMovie>() .ImplementedBy<Movie>(), Component .For<IMovie>() .ImplementedBy<RottenTomatoesMovie>() ); Amir Barylko - Advanced IoC MavenThought Inc.
  • 10. NAMING II • Assign unique names to registration container.Register( ... Component .For<IMovie>() .ImplementedBy<RottenTomatoesMovie>() .Named("RT") ); container.Resolve<IMovie>("RT"); Amir Barylko - Advanced IoC MavenThought Inc.
  • 11. JOGGING Installers Using Conventions Depend On Amir Barylko - Advanced IoC MavenThought Inc.
  • 12. INSTALLERS • Where do we put the registration code? • Encapsulation • Partition logic • Easy to maintain Amir Barylko - Advanced IoC MavenThought Inc.
  • 13. INSTALLER EXAMPLE container.Install( new EntitiesInstaller(), new RepositoriesInstaller(), // or use FromAssembly! FromAssembly.This(), FromAssembly.Named("MavenThought...."), FromAssembly.Containing<ServicesInstaller>(), FromAssembly.InDirectory(new AssemblyFilter("...")), FromAssembly.Instance(this.GetPluginAssembly()) ); Amir Barylko - Advanced IoC MavenThought Inc.
  • 14. XML CONFIG var res = new AssemblyResource("assembly://.../ ioc.xml") container.Install( Configuration.FromAppConfig(), Configuration.FromXmlFile("ioc.xml"), Configuration.FromXml(res) ); Amir Barylko - Advanced IoC MavenThought Inc.
  • 15. CONVENTIONS Classes .FromAssemblyContaining<IMovie>() .BasedOn<IMovie>() .WithService.Base() // Register the service .LifestyleTransient() // Transient lifestyle Amir Barylko - Advanced IoC MavenThought Inc.
  • 16. CONFIGURE COMPONENTS Classes .FromAssemblyContaining<IMovie>() .BasedOn<IMovie>() .LifestyleTransient() // Using naming to identify instances .Configure(r => r.Named(r.Implementation.Name)) Amir Barylko - Advanced IoC MavenThought Inc.
  • 17. DEPENDS ON var rtKey = @"the key goes here"; container.Register( Component .For<IMovieFactory>() .ImplementedBy<RottenTomatoesFactory>()    .DependsOn(Property.ForKey("apiKey").Eq(rtKey)) ); .DependsOn(new { apiKey = rtKey } ) // using anonymous class .DependsOn( new Dictionary<string,string>{ {"APIKey", twitterApiKey}}) // using dictionary Amir Barylko - Advanced IoC MavenThought Inc.
  • 18. SERVICE OVERRIDE container.Register(   Component .For<IMovieFactory>() .ImplementedBy<IMDBMovieFactory>() .Named(“imdbFactory”)   Component .For<IMovieRepository>() .ImplementedBy<SimpleMovieRepository>()      .DependsOn(Dependency.OnComponent("factory", "imdbFactory")) ); Amir Barylko - Advanced IoC MavenThought Inc.
  • 19. RUN FOREST! RUN! Startable Facility Interface Based Factories Castle AOP Amir Barylko - Advanced IoC MavenThought Inc.
  • 20. STARTABLE FACILITY • Allows objects to be started when they are created • And stopped when they are released • Start and stop methods have to be public, void and no parameters • You can use it with POCO objects specifying which method to use to start and stop Amir Barylko - Advanced IoC MavenThought Inc.
  • 21. STARTABLE CLASS public interface IStartable { void Start(); void Stop(); } var container = new WindsorContainer() .AddFacility<StartableFacility>() .Register( Component .For<IThing>() .ImplementedBy<StartableThing>() ); Amir Barylko - Advanced IoC MavenThought Inc.
  • 22. FACTORIES • Common pattern to create objects • But the IoC is some kind of factory too... • Each factory should use the IoC then.... • Unless we use Windsor!!!! Amir Barylko - Advanced IoC MavenThought Inc.
  • 23. TYPED FACTORIES • Create a factory based on an interface • Methods that return values are Resolve methods • Methods that are void are Release methods • Collection methods resolve to multiple components Amir Barylko - Advanced IoC MavenThought Inc.
  • 24. REGISTER FACTORY Kernel.AddFacility<TypedFactoryFacility>(); Register( Component .For<IMovie>() .ImplementedBy<NHMovie>() .LifeStyle.Transient, Component.For<IMovieFactory>().AsFactory() ); Amir Barylko - Advanced IoC MavenThought Inc.
  • 25. CASTLE AOP • Inject code around methods • Cross cutting concerns • Avoid mixing modelling and usage • Avoid littering the code with new requirements Amir Barylko - Advanced IoC MavenThought Inc.
  • 26. INTERCEPTORS Register( Component .For<LoggingInterceptor>() .LifeStyle.Transient, Component .For<IMovie>() .ImplementedBy<NHMovie>() .Interceptors(InterceptorReference .ForType<LoggingInterceptor>()).Anywhere .LifeStyle.Transient ); Amir Barylko - Advanced IoC MavenThought Inc.
  • 27. LOGGING public class LoggingInterceptor : IInterceptor { public void Intercept(IInvocation invocation) { Debug.WriteLine("Before execution"); invocation.Proceed(); Debug.WriteLine("After execution"); } } Amir Barylko - Advanced IoC MavenThought Inc.
  • 28. NOTIFY PROPERTY CHANGED Register( Component .For<NotifyPropertyChangedInterceptor>() .LifeStyle.Transient, Component .For<IMovieViewModel>() .ImplementedBy<MovieViewModel>() .Interceptors(InterceptorReference .ForType<NotifyPropertyChangedInterceptor>()) .Anywhere .LifeStyle.Transient ); Amir Barylko - Advanced IoC MavenThought Inc.
  • 29. QUESTIONS? Amir Barylko - TDD MavenThought Inc.
  • 30. RESOURCES • Contact: amir@barylko.com, @abarylko • Code & Slides: http://www.orthocoders.com/presentations • Castle Project Doc: http://docs.castleproject.org Amir Barylko - Advanced IoC MavenThought Inc.