80 likes | 171 Views
Samuli Haverinen, 29.9.2010. Inversion of Control. Motivation. Good architecture is (usually)… Loosely coupled Modular Service oriented How to avoid tight coupling? Separation of concerns Keep dependecies to a minimum. A not so good example. What’s wrong with this ?.
E N D
Samuli Haverinen, 29.9.2010 Inversion of Control
Motivation • Good architecture is (usually)… • Loosely coupled • Modular • Service oriented • How to avoid tight coupling? • Separation of concerns • Keep dependecies to a minimum
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!
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
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”); } }
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
IoC Container example • A very basic example of registering a type in Microsoft Unity