SlideShare uma empresa Scribd logo
1 de 30
Baixar para ler offline
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.

Mais conteúdo relacionado

Mais procurados

CDI Integration in OSGi - Emily Jiang
CDI Integration in OSGi - Emily JiangCDI Integration in OSGi - Emily Jiang
CDI Integration in OSGi - Emily Jiangmfrancis
 
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 Bosschaertmfrancis
 
081107 Sammy Eclipse Summit2
081107   Sammy   Eclipse Summit2081107   Sammy   Eclipse Summit2
081107 Sammy Eclipse Summit2mkempka
 
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
 
Android MvRx Framework 介紹
Android MvRx Framework 介紹Android MvRx Framework 介紹
Android MvRx Framework 介紹Kros Huang
 
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 GlassFishArun Gupta
 
Spring - CDI Interop
Spring - CDI InteropSpring - CDI Interop
Spring - CDI InteropRay Ploski
 
RIBs - Fragments which work
RIBs - Fragments which workRIBs - Fragments which work
RIBs - Fragments which workDmitry Zaytsev
 

Mais procurados (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
 

Destaque

castle-windsor-ioc-demo
castle-windsor-ioc-democastle-windsor-ioc-demo
castle-windsor-ioc-demoAmir Barylko
 
Dependency injection& comparative study
Dependency injection& comparative studyDependency injection& comparative study
Dependency injection& comparative studypallavs20
 
User stories deep dive
User stories deep diveUser stories deep dive
User stories deep diveAmir Barylko
 
Elm: delightful web development
Elm: delightful web developmentElm: delightful web development
Elm: delightful web developmentAmir Barylko
 

Destaque (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
 

Semelhante a ioc-castle-windsor

Codemash-advanced-ioc-castle-windsor
Codemash-advanced-ioc-castle-windsorCodemash-advanced-ioc-castle-windsor
Codemash-advanced-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
 
PRDCW-avent-aggregator
PRDCW-avent-aggregatorPRDCW-avent-aggregator
PRDCW-avent-aggregatorAmir Barylko
 
Introduction to IoC Container
Introduction to IoC ContainerIntroduction to IoC Container
Introduction to IoC ContainerGyuwon Yi
 
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
 
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
 
The Basic Concept Of IOC
The Basic Concept Of IOCThe Basic Concept Of IOC
The Basic Concept Of IOCCarl Lu
 
prdc10-tdd-patterns
prdc10-tdd-patternsprdc10-tdd-patterns
prdc10-tdd-patternsAmir Barylko
 
springtraning-7024840-phpapp01.pdf
springtraning-7024840-phpapp01.pdfspringtraning-7024840-phpapp01.pdf
springtraning-7024840-phpapp01.pdfBruceLee275640
 
Istio Upgrade Field Guide IstioCon2022.pdf
Istio Upgrade Field Guide IstioCon2022.pdfIstio Upgrade Field Guide IstioCon2022.pdf
Istio Upgrade Field Guide IstioCon2022.pdfRam Vennam
 
Cpl12 continuous integration
Cpl12 continuous integrationCpl12 continuous integration
Cpl12 continuous integrationAmir Barylko
 
Agile requirements
Agile requirementsAgile requirements
Agile requirementsAmir Barylko
 
Docker presentasjon java bin
Docker presentasjon java binDocker presentasjon java bin
Docker presentasjon java binOlve Hansen
 
every-day-automation
every-day-automationevery-day-automation
every-day-automationAmir Barylko
 
Continous Delivering a PHP application
Continous Delivering a PHP applicationContinous Delivering a PHP application
Continous Delivering a PHP applicationJavier López
 

Semelhante a 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
 

Mais de Amir Barylko

Functional converter project
Functional converter projectFunctional converter project
Functional converter projectAmir 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
 
Beutiful javascript with coffeescript
Beutiful javascript with coffeescriptBeutiful javascript with coffeescript
Beutiful javascript with coffeescriptAmir Barylko
 
PRDC12 advanced design patterns
PRDC12 advanced design patternsPRDC12 advanced design patterns
PRDC12 advanced design patternsAmir Barylko
 
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 coffeescriptAmir Barylko
 

Mais 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
 

Último

Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024The Digital Insurer
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
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
 
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
 
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
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
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
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
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)wesley chun
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
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...apidays
 

Último (20)

Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
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...
 
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...
 
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
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
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
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
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)
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
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...
 

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.