Download
samuli haverinen 29 9 2010 n.
Skip this Video
Loading SlideShow in 5 Seconds..
Inversion of Control PowerPoint Presentation
Download Presentation
Inversion of Control

Inversion of Control

68 Vues Download Presentation
Télécharger la présentation

Inversion of Control

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

  1. Samuli Haverinen, 29.9.2010 Inversion of Control

  2. Motivation • Good architecture is (usually)… • Loosely coupled • Modular • Service oriented • How to avoid tight coupling? • Separation of concerns • Keep dependecies to a minimum

  3. A notsogoodexample • What’swrong with this? public class EmailService { public void SendEmail(string to, string subject, string message) { // Send the email… } } public class User { public void CreateUser(string username, string email) { EmailService emailService = new EmailService(); emailService.SendMail(email, ”hi”, ”A not so good example”); } } • Answer: it’stightlycoupled!

  4. Basics • Inversion of Control is a design pattern • Every class is given its dependecies through the constructor • Every dependency is expressed as an interface! • Interfaces are registered with a particular implementation at application intialization • IoC container passes the registered implementations to constructors

  5. A betterexample public interface IMessagingService { void SendMessage(string to, string subject, string body); } public class MyEmailService : IMessagingService { // A class containing SendMessage method that sends the email } public class User { IMessagingService _messagingService; public User(IMessagingService messagingService) { this._messagingService = messagingService; } public void CreateUser(string username, string email) { this._messagingService.SendMessage(email, ”hi”, ”A better example”); } }

  6. IoC Containers • Containers contain interfaces and their implementations • Containers inject the dependencies to constructors, i.e. the concrete implementations when an interface is requried • Interfaces and implementations can usually be configured in code or in a separate xml file • There are a few widely used IoC containers like Microsoft Unity or Castle Windsor. There is no need to implement your own! • Containers also manage object lifetimes • Singleton is used as default

  7. IoC Container example • A very basic example of registering a type in Microsoft Unity

  8. Questions?