SlideShare una empresa de Scribd logo
1 de 30
Descargar para leer sin conexión
AMIR BARYLKO

                    ADVANCED IOC
                      WINDSOR
                       CASTLE



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.

Más contenido relacionado

La actualidad más candente

CodeCamp 2012-mvc-vs-ror-2
CodeCamp 2012-mvc-vs-ror-2CodeCamp 2012-mvc-vs-ror-2
CodeCamp 2012-mvc-vs-ror-2Amir Barylko
 
prdc10-Bdd-real-world
prdc10-Bdd-real-worldprdc10-Bdd-real-world
prdc10-Bdd-real-worldAmir Barylko
 
Cpl12 continuous integration
Cpl12 continuous integrationCpl12 continuous integration
Cpl12 continuous integrationAmir Barylko
 
PRDC11-tdd-common-mistakes
PRDC11-tdd-common-mistakesPRDC11-tdd-common-mistakes
PRDC11-tdd-common-mistakesAmir Barylko
 
Aki Salmi - Refactoring legacy code: a true story @ I T.A.K.E. Unconference 2...
Aki Salmi - Refactoring legacy code: a true story @ I T.A.K.E. Unconference 2...Aki Salmi - Refactoring legacy code: a true story @ I T.A.K.E. Unconference 2...
Aki Salmi - Refactoring legacy code: a true story @ I T.A.K.E. Unconference 2...Mozaic Works
 
Android java fx-jme@jug-lugano
Android java fx-jme@jug-luganoAndroid java fx-jme@jug-lugano
Android java fx-jme@jug-luganoFabrizio Giudici
 
Automated UI test on mobile - with Cucumber/Calabash
Automated UI test on mobile - with Cucumber/CalabashAutomated UI test on mobile - with Cucumber/Calabash
Automated UI test on mobile - with Cucumber/CalabashNiels Frydenholm
 
20110903 candycane
20110903 candycane20110903 candycane
20110903 candycaneYusuke Ando
 
Getting your mobile test automation process in place - using Cucumber and Cal...
Getting your mobile test automation process in place - using Cucumber and Cal...Getting your mobile test automation process in place - using Cucumber and Cal...
Getting your mobile test automation process in place - using Cucumber and Cal...Niels Frydenholm
 
Intro to Continuous Integration at SoundCloud
Intro to Continuous Integration at SoundCloudIntro to Continuous Integration at SoundCloud
Intro to Continuous Integration at SoundCloudgarriguv
 

La actualidad más candente (11)

CodeCamp 2012-mvc-vs-ror-2
CodeCamp 2012-mvc-vs-ror-2CodeCamp 2012-mvc-vs-ror-2
CodeCamp 2012-mvc-vs-ror-2
 
prdc10-Bdd-real-world
prdc10-Bdd-real-worldprdc10-Bdd-real-world
prdc10-Bdd-real-world
 
Cpl12 continuous integration
Cpl12 continuous integrationCpl12 continuous integration
Cpl12 continuous integration
 
PRDC11-tdd-common-mistakes
PRDC11-tdd-common-mistakesPRDC11-tdd-common-mistakes
PRDC11-tdd-common-mistakes
 
obs-tdd-intro
obs-tdd-introobs-tdd-intro
obs-tdd-intro
 
Aki Salmi - Refactoring legacy code: a true story @ I T.A.K.E. Unconference 2...
Aki Salmi - Refactoring legacy code: a true story @ I T.A.K.E. Unconference 2...Aki Salmi - Refactoring legacy code: a true story @ I T.A.K.E. Unconference 2...
Aki Salmi - Refactoring legacy code: a true story @ I T.A.K.E. Unconference 2...
 
Android java fx-jme@jug-lugano
Android java fx-jme@jug-luganoAndroid java fx-jme@jug-lugano
Android java fx-jme@jug-lugano
 
Automated UI test on mobile - with Cucumber/Calabash
Automated UI test on mobile - with Cucumber/CalabashAutomated UI test on mobile - with Cucumber/Calabash
Automated UI test on mobile - with Cucumber/Calabash
 
20110903 candycane
20110903 candycane20110903 candycane
20110903 candycane
 
Getting your mobile test automation process in place - using Cucumber and Cal...
Getting your mobile test automation process in place - using Cucumber and Cal...Getting your mobile test automation process in place - using Cucumber and Cal...
Getting your mobile test automation process in place - using Cucumber and Cal...
 
Intro to Continuous Integration at SoundCloud
Intro to Continuous Integration at SoundCloudIntro to Continuous Integration at SoundCloud
Intro to Continuous Integration at SoundCloud
 

Similar a Codemash-advanced-ioc-castle-windsor

ioc-castle-windsor
ioc-castle-windsorioc-castle-windsor
ioc-castle-windsorAmir Barylko
 
Process Matters (Cloud2Days / Java2Days conference))
Process Matters (Cloud2Days / Java2Days conference))Process Matters (Cloud2Days / Java2Days conference))
Process Matters (Cloud2Days / Java2Days conference))dev2ops
 
Introduction to IoC Container
Introduction to IoC ContainerIntroduction to IoC Container
Introduction to IoC ContainerGyuwon Yi
 
PRDCW-avent-aggregator
PRDCW-avent-aggregatorPRDCW-avent-aggregator
PRDCW-avent-aggregatorAmir Barylko
 
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; CoffeescriptAmir Barylko
 
Micronaut: Changing the Micro Future
Micronaut: Changing the Micro FutureMicronaut: Changing the Micro Future
Micronaut: Changing the Micro FutureZachary Klein
 
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 Saadeyoungculture
 
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.1Codecamp Romania
 
springtraning-7024840-phpapp01.pdf
springtraning-7024840-phpapp01.pdfspringtraning-7024840-phpapp01.pdf
springtraning-7024840-phpapp01.pdfBruceLee275640
 
Agile requirements
Agile requirementsAgile requirements
Agile requirementsAmir Barylko
 
The Basic Concept Of IOC
The Basic Concept Of IOCThe Basic Concept Of IOC
The Basic Concept Of IOCCarl Lu
 
Istio Upgrade Field Guide IstioCon2022.pdf
Istio Upgrade Field Guide IstioCon2022.pdfIstio Upgrade Field Guide IstioCon2022.pdf
Istio Upgrade Field Guide IstioCon2022.pdfRam Vennam
 
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.VitaliyMakogon
 
Docker presentasjon java bin
Docker presentasjon java binDocker presentasjon java bin
Docker presentasjon java binOlve Hansen
 
Need(le) for Speed - Effective Unit Testing for Java EE
Need(le) for Speed - Effective Unit Testing for Java EENeed(le) for Speed - Effective Unit Testing for Java EE
Need(le) for Speed - Effective Unit Testing for Java EEhwilming
 
Spring training
Spring trainingSpring training
Spring trainingTechFerry
 
Immutable Infrastructure & Rethinking Configuration - Interop 2019
Immutable Infrastructure & Rethinking Configuration - Interop 2019Immutable Infrastructure & Rethinking Configuration - Interop 2019
Immutable Infrastructure & Rethinking Configuration - Interop 2019RackN
 

Similar a Codemash-advanced-ioc-castle-windsor (20)

ioc-castle-windsor
ioc-castle-windsorioc-castle-windsor
ioc-castle-windsor
 
Process Matters (Cloud2Days / Java2Days conference))
Process Matters (Cloud2Days / Java2Days conference))Process Matters (Cloud2Days / Java2Days conference))
Process Matters (Cloud2Days / Java2Days conference))
 
Introduction to IoC Container
Introduction to IoC ContainerIntroduction to IoC Container
Introduction to IoC Container
 
PRDCW-avent-aggregator
PRDCW-avent-aggregatorPRDCW-avent-aggregator
PRDCW-avent-aggregator
 
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
 
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
 
springtraning-7024840-phpapp01.pdf
springtraning-7024840-phpapp01.pdfspringtraning-7024840-phpapp01.pdf
springtraning-7024840-phpapp01.pdf
 
Agile requirements
Agile requirementsAgile requirements
Agile requirements
 
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
 
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
 
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.
 
Docker presentasjon java bin
Docker presentasjon java binDocker presentasjon java bin
Docker presentasjon java bin
 
Need(le) for Speed - Effective Unit Testing for Java EE
Need(le) for Speed - Effective Unit Testing for Java EENeed(le) for Speed - Effective Unit Testing for Java EE
Need(le) for Speed - Effective Unit Testing for Java EE
 
Tdd patterns1
Tdd patterns1Tdd patterns1
Tdd patterns1
 
Spring training
Spring trainingSpring training
Spring training
 
Immutable Infrastructure & Rethinking Configuration - Interop 2019
Immutable Infrastructure & Rethinking Configuration - Interop 2019Immutable Infrastructure & Rethinking Configuration - Interop 2019
Immutable Infrastructure & Rethinking Configuration - Interop 2019
 

Más de Amir Barylko

Functional converter project
Functional converter projectFunctional converter project
Functional converter projectAmir Barylko
 
Elm: delightful web development
Elm: delightful web developmentElm: delightful web development
Elm: delightful web developmentAmir Barylko
 
User stories deep dive
User stories deep diveUser stories deep dive
User stories deep diveAmir Barylko
 
Coderetreat hosting training
Coderetreat hosting trainingCoderetreat hosting training
Coderetreat hosting trainingAmir Barylko
 
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) awesomenessAmir Barylko
 
What's new in c# 6
What's new in c# 6What's new in c# 6
What's new in c# 6Amir Barylko
 
Who killed object oriented design?
Who killed object oriented design?Who killed object oriented design?
Who killed object oriented design?Amir Barylko
 
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 sideAmir Barylko
 
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 productivityAmir Barylko
 
Acceptance Test Driven Development
Acceptance Test Driven DevelopmentAcceptance Test Driven Development
Acceptance Test Driven DevelopmentAmir Barylko
 
Agile requirements
Agile requirementsAgile requirements
Agile requirementsAmir Barylko
 
Agile teams and responsibilities
Agile teams and responsibilitiesAgile teams and responsibilities
Agile teams and responsibilitiesAmir Barylko
 
Beutiful javascript with coffeescript
Beutiful javascript with coffeescriptBeutiful javascript with coffeescript
Beutiful javascript with coffeescriptAmir Barylko
 
SDEC12 Beautiful javascript with coffeescript
SDEC12 Beautiful javascript with coffeescriptSDEC12 Beautiful javascript with coffeescript
SDEC12 Beautiful javascript with coffeescriptAmir Barylko
 

Más de Amir Barylko (20)

Functional converter project
Functional converter projectFunctional converter project
Functional converter project
 
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
 
No estimates
No estimatesNo estimates
No estimates
 
User stories deep dive
User stories deep diveUser stories deep dive
User stories deep dive
 
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
 

Último

Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
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 CVKhem
 
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 WorkerThousandEyes
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
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...Martijn de Jong
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
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
 
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...DianaGray10
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 

Último (20)

Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
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
 
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
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
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...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
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...
 
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...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 

Codemash-advanced-ioc-castle-windsor

  • 1. AMIR BARYLKO ADVANCED IOC WINDSOR CASTLE 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.